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

C# DataGridView 多表查詢綁定:需設置 AutoGenerateColumns 或手動列映射

     編輯:程式設計綜合問答

問題代碼

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]; // 顯示空白或異常

原因與解決

  1. 列名重複/無效:SQL 別名缺失,導致列名為 Expr1、Expr2 或重名;
  2. 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];
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved