【问题标题】:DataSet to DataGridView with pre-defined Columns具有预定义列的 DataSet 到 DataGridView
【发布时间】:2011-11-14 22:23:35
【问题描述】:

我有一个在 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

【问题讨论】:

    标签: c# winforms .net-3.5 datagridview


    【解决方案1】:

    您需要将 DataTable 中的列与 DataGridView 中的列相关联。

    通过使用您希望在该 DGV 列中显示的 DataTable 中的列名称更新 DGV 列的 DataPropertyName 属性来执行此操作。例如,将 DGV 中帐号的 DataPropertyName 属性设置为 acctNum。请注意,您可以通过“编辑列”对话框在设计器中轻松执行此操作(通过在设计器中右键单击 DGV 并从弹出窗口中选择“编辑列...”来打开对话框)。

    请注意,您需要将 DataGridView 的 AutoGenerateColumns 设置为 false 以防止其自行创建列。我相信您只能通过代码进行此设置。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-17
      • 1970-01-01
      • 1970-01-01
      • 2013-04-13
      • 1970-01-01
      • 2011-05-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多