我有一个在 WinForms 项目中设置的 DataGridView。列都在设计器文件中定义。当我运行 SQL 时,DataGridView 中的列将替换为查询中的列名。
如何保留由 DataGridView 定义的列,并将数据集中的行从数据集添加到 GridView。
//Columns as they appear in the DataGridView
Name | Address | City | State | Zip | Account Num |
//Populate the gridView
DataSet ds = Account.search(strSearch);
accountGrid.DataSource = ds.Tables[0];
//query
string sql = "SELECT distinct acctNum, name, address, city, state, zip from accounts";
return DataService.GetDataSet(sql);
//The End Result of the columns
acctNum | name | address |city | state | zip
最佳答案
您需要将 DataTable 中的列与 DataGridView 中的列相关联。
通过将 DGV 列的 DataPropertyName
属性更新为您希望在该 DGV 列中显示的 DataTable 中的列名称来执行此操作。例如,将帐号的 DGV 中的 DataPropertyName
属性设置为 acctNum
。请注意,您可以通过“编辑列”对话框在设计器中轻松执行此操作(通过在设计器中右键单击 DGV 并从弹出窗口中选择“编辑列...”来打开对话框)。
请注意,您需要将 DataGridView 的 AutoGenerateColumns
设置为 false
以防止它自己创建列。我相信您只能通过代码进行此设置。
关于c# - DataSet 到具有预定义列的 DataGridView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7381374/