【发布时间】: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