首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

ADO.NET DataSet Tables 索引越界:Tables[1] 應為 Tables[0] 的零基陷阱

     編輯:程式設計綜合問答

錯誤代碼

DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds, "student");  // 表名為 "student"
MessageBox.Show(ds.Tables[1].Columns.ToString()); // ❌ 索引 1 越界

運行拋出 IndexOutOfRangeException: Cannot find table 1。

根本原因

DataSet.Tables 集合是零基索引。da.Fill(ds, "student") 只添加**一張表** (索引 0),名稱為 "student"。訪問 Tables[1] 嘗試獲取第二張表,不存在。

正確訪問方式

// 方式一:索引 0 (按填充順序)
DataTable dt = ds.Tables[0];

// 方式二:表名 (推薦,語義清晰、順序無關)
DataTable dt = ds.Tables["student"];

// 方式三:遍歷 (多表場景)
foreach (DataTable table in ds.Tables) {
    Console.WriteLine(table.TableName);
    foreach (DataColumn col in table.Columns) { ... }
}

完整修正代碼

SqlConnection cn = new SqlConnection(app);
SqlCommand cmd = cn.CreateCommand();
cmd.CommandText = "select * from Accountnumber where name='admin'";
cmd.CommandType = CommandType.Text;

DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;

da.Fill(ds, "student");  // 只填充一張表

// ✅ 正確訪問
DataTable dt = ds.Tables["student"];  // 或 ds.Tables[0]
MessageBox.Show($"表名: {dt.TableName}, 列數: {dt.Columns.Count}, 行數: {dt.Rows.Count}");

// 遍歷數據演示
foreach (DataRow row in dt.Rows) {
    Console.WriteLine(string.Join(", ", row.ItemArray));
}

相關最佳實踐

  • 始終用表名訪問:ds.Tables["student"],避免順序變更導致索引錯誤;
  • Fill 多表時指定不同表名:da.Fill(ds, "users"); da2.Fill(ds, "orders");;
  • 檢查表是否存在:if (ds.Tables.Contains("student"));
  • 釋放資源:using (cn) using (cmd) using (da) { ... } 確保連接關閉。

總結

DataSet.Tables 為零基集合,單表填充僅有 Tables[0]。改用 Tables["表名"] 既安全又可讀。養成「名稱索引優於數字索引」的習慣,消除此類低級錯誤。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved