【问题标题】:New added column to the DataTable doesn't show at correct index in DataGridViewDataTable 中新添加的列未显示在 DataGridView 中的正确索引处
【发布时间】:2018-04-19 13:09:08
【问题描述】:

我有一个 DataTable 设置为 DataGridView 的 DataSource。我像这样在特定索引处向 DataTable 添加一列;

DataSource.Columns.Add(columnName).SetOrdinal(index);

但是,用户界面会显示添加到末尾的新列(即一直到右侧)。当断点进入并仔细查看时,我可以看到我的 DataTable 和 DataGridView 项目都在正确的位置索引了新列。这对我来说没有意义,因为我在 UI 中查看的是 DataGridView。

我已尝试执行以下两项操作来刷新 DataSource,但正如我所说,调试时我可以看到 DataGridView 在正确的索引处有新列。它只是不显示 AT 这个索引。

DataGrid.Refresh();
DataGrid.Update();

更新

看起来尚未更新的字段是 DisplayIndex。我在这里遗漏了一个步骤,还是只需要在添加列时手动更新此索引?我假设 DataTable DataSource 也会覆盖 DisplayIndex?

更新 2

看起来很老套,但这很有效。如果有更好的方法,我仍然会感兴趣。

private void ensureOrdering()
    {
        foreach (DataGridViewColumn col in dgvData.Columns)
        {
            col.DisplayIndex = col.Index;
        }
    }

MCVE

在表单上有一个DataGridView 和一个Button,如果您在表单的Load 事件中添加一些列并将DataGridView 绑定到表,然后在按钮的Click 事件中插入另一列,您将看到该列将显示在列列表的末尾:

DataTable dt = new DataTable();
private void Form1_Load(object sender, EventArgs e)
{
    dt.Columns.Add("X");
    dt.Columns.Add("Y");
    this.dataGridView1.DataSource = dt;
}
private void button1_Click(object sender, EventArgs e)
{
    dt.Columns.Add("Z").SetOrdinal(0);
}

【问题讨论】:

标签: c# .net winforms datagridview datatable


【解决方案1】:

作为替代方案,您可以将DataSource 设置为null 并将其设置回您的数据表:

dataGridView1.DataSource = null;
dataGridView1.DataSource = dt;

注意:DataGridView 接收到底层IBindingListListChange 事件时,它会检查更改是否是由于属性描述符中的添加、删除或更改,然后它会调用一些私有的有关更改数据源元数据的方法。如果你喜欢阅读源代码,请开始here

【讨论】:

  • 如果有更好的方法,我仍然会感兴趣。 ← 在这个主题上做得更好有点基于意见,但我相信我分享的是更好的方法:)
猜你喜欢
  • 1970-01-01
  • 2016-11-05
  • 1970-01-01
  • 2015-10-12
  • 2016-08-28
  • 2016-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多