問題代碼
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";
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
DataSet ds = new DataSet();
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0]; // 顯示空白或異常
原因與解決
- 列名重複/無效:SQL 別名缺失,導致列名為
Expr1、Expr2 或重名;
- DataGridView 未自動生成列:
AutoGenerateColumns = false 且未手動定義 Columns。
修正 SQL
SELECT a.col2 AS A_Col2, a.col3 AS A_Col3, b.col2 AS B_Col2, b.col3 AS B_Col3
FROM a JOIN c ON a.id = c.id JOIN b ON b.id = c.id
綁定代碼
dataGridView1.AutoGenerateColumns = true; // 或手動添加 DataGridViewTextBoxColumn 映射 DataPropertyName
dataGridView1.DataSource = ds.Tables[0];