【问题标题】:someDataGridView.DataSource = someDataTable combines both tables, creates additional columnssomeDataGridView.DataSource = someDataTable 合并两个表,创建附加列
【发布时间】:2013-11-06 15:57:11
【问题描述】:

全部。

我目前正在开发一个 C# Winforms 项目。将数据应用到 DataGridView 后,我遇到了一个奇怪的问题,即让它们保持正确的格式。

基本上,我得到的是这个......

DataGridView dgMainTable;
DataTable dtOtherTable;

...

/* Add and format columns for BOTH objects.  They're almost the same except for column widths */

...

/*Add data one row at a time to dtOtherTable*/

...

//Here's the kicker...
dgMainTable.DataSource = dtOtherTable;

完成所有这些后,我希望 dgMainTable 会填充来自 dtOtherTable 的数据。但是,我得到的是一些奇怪的列集合,据我所知,这两个表合并为一个表。所以,就我而言,我有六列而不是我期望的三列。

是的,我已经能够通过不格式化第一个表格来解决这个问题。如果我为此注释掉代码,则数据会按预期分配,但是我无法控制第一个表结构。结构不应由表定义。鉴于我的代码结构,这只是一个糟糕的地方。如何在保留主表的结构和格式的同时将数据从另一个表移动到主 DataGridView?

【问题讨论】:

    标签: c# winforms datatable


    【解决方案1】:

    如果您自己设计 dgMainTable 并想保留它,您必须在关闭AutoGenerateColumns 的情况下自己绑定 数据(打开时没关系,但是当您的所有列都是手动设置时,在这种情况下不需要)。我想您的dgMainTable 有 3 列 Column1Column2Column3,而您的 dtOtherTable 中的相应列分别是 Col1Col2Col3。您必须添加以下代码(在dtOtherTabledgMainTable 之间手动绑定数据):

    dgMainTable.Columns["Column1"].DataPropertyName = "Col1";
    dgMainTable.Columns["Column2"].DataPropertyName = "Col2";
    dgMainTable.Columns["Column3"].DataPropertyName = "Col3";
    //bind data
    dgMainTable.DataSource = dtOtherTable;
    

    【讨论】:

      猜你喜欢
      • 2020-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-20
      • 1970-01-01
      • 1970-01-01
      • 2020-01-01
      • 1970-01-01
      相关资源
      最近更新 更多