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"],避免順序變更導致索引錯誤;da.Fill(ds, "users"); da2.Fill(ds, "orders");;if (ds.Tables.Contains("student"));using (cn) using (cmd) using (da) { ... } 確保連接關閉。DataSet.Tables 為零基集合,單表填充僅有 Tables[0]。改用 Tables["表名"] 既安全又可讀。養成「名稱索引優於數字索引」的習慣,消除此類低級錯誤。