【问题标题】:Updating DataGridView after changing data source during run-time在运行时更改数据源后更新 DataGridView
【发布时间】:2021-07-27 04:44:13
【问题描述】:
public void sortAssets(string assetType)
    {
        DataTable newDataTable = new DataTable();
        foreach(DataRow row in table.Rows)
        {
            if ((string)row["assetType"] == assetType)
            {
                string test = (string)row["assetType"];
                newDataTable.ImportRow(row);
            }
        }
        dataGridViewAssets.DataSource = null;
        dataGridViewAssets.DataSource = newDataTable;
        dataGridViewAssets.Refresh();
    }

以上是从我正在处理的程序中提取的一段代码。 我想在运行时将数据源更改为newDataTable。为此,我首先使用dataGridViewAssets.DataSource = null; 清除了datagridview。然后,我更改了数据源(dataGridViewAssets.DataSource = newDataTable;)。最后我通过dataGridViewAssets.Refresh();刷新了datagridview。

但是,可视化数据网格视图不会更新。相反,其中的所有数据都会被删除并保持空白。

这里有什么问题,必须改变什么?

【问题讨论】:

  • 你确定newDataTable 真的有数据吗?此外,与手动将“过滤”行添加到新表相比,您没有得到原始 table 的“过滤”版本是否有某些原因?
  • 如前所述,您可以过滤 DataTable 以显示符合某些条件的行。 -- 您还可以使用 BindingSource 作为 DGV 的 .DataSource 并使用其排序/过滤功能。 -- 注意Refresh()重绘控件的图形,与数据或数据绑定无关。 -- 在 DataGridView 中,如果您想用另一个 DataTable 替换(实际需要时,不在此处),设置 DataSource = null 无关紧要:只需设置新的 DataTable。
  • 为什么您的方法在执行过滤而不是排序时称为 sortAsserts?也没有必要将 DataSource 设置为 null

标签: c# .net winforms datagridview


【解决方案1】:

除非您特别需要克隆行,否则这会简单得多:

public void FilterAssets(string assetType) {
  (dataGridViewAssets.DataSource as DataTable).DefaultView.RowFilter = "$[assetType] = '{assetType}'";
}

如果您基于绑定源制作了 DGV,那么它是

public void FilterAssets(string assetType) {
  (dataGridViewAssets.DataSource as BindingSource).Filter = "$[assetType] = '{assetType}'";
}

【讨论】:

  • 如果assetType 将包含撇号,将它们加倍以转义它们
猜你喜欢
  • 2017-05-27
  • 2012-04-15
  • 1970-01-01
  • 1970-01-01
  • 2021-05-06
  • 1970-01-01
  • 2010-09-20
  • 1970-01-01
相关资源
最近更新 更多