原始代碼問題
string sql = "select a.2, a.3, b.2, b.3 from a, b, c where a.1=c.1 and b.1=c.1";
DataSet ds1 = new DataSet();
DataTable dt = new DataTable();
DataSet ds2 = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
da.Fill(ds1);
dt = ds1.Tables[0].Copy();
ds2.Tables.Add(dt);
dataGridView1.DataSource = ds2.Tables[0];
問題分析
- SQL 列名
a.2 非法,應用別名或方括號 [2]。
- 創建
ds2 並 Copy() 多餘,直接綁定 ds1.Tables[0] 即可。
DataGridView 需設置 AutoGenerateColumns=true (默認) 或手動定義列映射 DataPropertyName。
修正代碼
string sql = @"SELECT a.[col2] AS A_Col2, a.[col3] AS A_Col3,
b.[col2] AS B_Col2, b.[col3] AS B_Col3
FROM TableA a
JOIN TableC c ON a.id = c.a_id
JOIN TableB b ON b.id = c.b_id";
using (SqlConnection conn = new SqlConnection(connStr))
using (SqlDataAdapter da = new SqlDataAdapter(sql, conn)) {
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
// 若需固定列順序/標題,可在設計器或代碼中添加 DataGridViewColumn 並設置 DataPropertyName
}
關鍵點
- 使用
using 確保連接關閉。
- SQL 用別名避免列名衝突。
- 直接綁定
DataTable,簡潔高效。