【问题标题】:Merging two Datatables with different column names合并具有不同列名的两个数据表
【发布时间】:2019-02-07 14:57:24
【问题描述】:

我有两个列名不同的数据表,因为它们是从两个不同的 MySQL 表中填充的

  • DataTable1 有IDNameBrandGenreCreator
  • DataTable2 有IDNameBrandTypeEntryCreator

我想合并它们,这样我就可以在DataGridView1 中显示它们。我做了

DataTable2.Columns(3).ColumnName = "Genre" DataTable2.Columns(4).ColumnName = "Creator"

然后 DataTable1.Merge(DataTable2, false, MissingSchemaAction.Add) BindingSource1.DataSource = DataTable1 DataGridView1.Source = BindingSource1

但在显示时,它只显示来自DataTable2的数据

【问题讨论】:

  • 您是否已将两个表的 PrimaryKey 值设置为 ID 字段?
  • 我使用 `MySqlAdapter 来填充它们。如果它从我的 MariaDB 数据库中复制 PK,我会这样做,否则,我不会。 (我没有将 ID 列声明为 Primay Key)
  • 您能否简单地将您在 MySqlDataAdapter 中的查询更改为第二个表具有与第一个表相同的列名称? IE SELECT .... Type as Brand,EntryCreator as Creator ..... 这样两个表将具有相同的列名
  • 如果设置 DataTable2.PrimaryKey = null; 会发生什么DataTable1.PrimaryKey=null; ?
  • 对不起,我的意思是没有什么不为空

标签: vb.net datagridview datatable


【解决方案1】:

问题可能是由于 Merge 使用表的 PrimaryKey 查找要更新的现有记录,如果找不到则添加新记录。如果是这种情况,那么您应该禁用在通过数据适配器填充表时检索到的 PrimaryKey 信息。

dataTable1.PrimaryKey = Nothing
dataTable2.PrimaryKey = Nothing
dataTable1.Merge(dataTable2, false, MissingSchemaAction.Add)
....

现在 Merge 找不到匹配项,因此 dataTable2 中的每条记录都添加到 dataTable1 中。但是,我应该警告您密切关注此 dataTable1 上其他操作的性能和正确性。
现在没有设置 PrimaryKey,这可能是更新和删除行时出现问题的原因(如果你当然有这些操作)

【讨论】:

  • .PrimaryKey 设置为 2 列会有所帮助吗? OP说它们是不同种类的产品。也许 ID 和 Genre/Type 可以提供唯一性。然后至少可以更新或删除一条记录。
  • 有可能,但我们没有足够的关于数据集和形成约束的信息
猜你喜欢
  • 2023-04-03
  • 2021-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-18
  • 1970-01-01
  • 1970-01-01
  • 2015-03-21
相关资源
最近更新 更多