DataGridView 在 TabControl 中丢失了 Datatable 的一行
DataGridView loses one row from Datatable in TabControl
我有一个应用程序使用 DataGridView
坐在 TabPage
和 DataTable
作为数据源。我创建 DataTable
,填充行并在启动时将 DataGridView's
数据源设置为 DataTable
。像这样
aData.Columns.Add("Description", typeof(string));
aData.Columns.Add("OID", typeof(string));
aData.Columns.Add("Value", typeof(string));
aData.Rows.Add(new object[] { "Row 1", 0, null });
aData.Rows.Add(new object[] { "Row 2", 1, null });
aData.AcceptChanges();
dgTest.DataSource = aData;
我有一个线程执行并触发一个事件,该事件将更新 DataTable
值。
一切正常,直到您开始在 TabPages
之间切换,然后 DataGrid
丢失其中一行。如果您单击 header 列对行进行排序,它会弹出。但是在 TabPages
之间切换,它又消失了。
如果查询 DataGrid,Rows 属性只显示 1 行,但 DataTable
仍显示 2 行。
我对为什么会发生这种情况以及我是否做错了什么感到有点困惑。我添加了一个具有相同行为的示例应用程序 here
您需要从 UI 线程调用 AcceptChanges
。在您的代码中进行下一个更改:
// aData.AcceptChanges(); <- change this to the code below inside your OnResult event
this.BeginInvoke(new Action(() => { aData.AcceptChanges(); }));
您的活动现在应该如下所示:
void rm_OnResult(int Row, int Value)
{
DataRow[] dr;
dr = aData.Select("OID = '" + Row + "'");
dr[0]["Value"] = Value.ToString("#,###.00");
this.BeginInvoke(new Action(() => { aData.AcceptChanges(); }));
}
我有一个应用程序使用 DataGridView
坐在 TabPage
和 DataTable
作为数据源。我创建 DataTable
,填充行并在启动时将 DataGridView's
数据源设置为 DataTable
。像这样
aData.Columns.Add("Description", typeof(string));
aData.Columns.Add("OID", typeof(string));
aData.Columns.Add("Value", typeof(string));
aData.Rows.Add(new object[] { "Row 1", 0, null });
aData.Rows.Add(new object[] { "Row 2", 1, null });
aData.AcceptChanges();
dgTest.DataSource = aData;
我有一个线程执行并触发一个事件,该事件将更新 DataTable
值。
一切正常,直到您开始在 TabPages
之间切换,然后 DataGrid
丢失其中一行。如果您单击 header 列对行进行排序,它会弹出。但是在 TabPages
之间切换,它又消失了。
如果查询 DataGrid,Rows 属性只显示 1 行,但 DataTable
仍显示 2 行。
我对为什么会发生这种情况以及我是否做错了什么感到有点困惑。我添加了一个具有相同行为的示例应用程序 here
您需要从 UI 线程调用 AcceptChanges
。在您的代码中进行下一个更改:
// aData.AcceptChanges(); <- change this to the code below inside your OnResult event
this.BeginInvoke(new Action(() => { aData.AcceptChanges(); }));
您的活动现在应该如下所示:
void rm_OnResult(int Row, int Value)
{
DataRow[] dr;
dr = aData.Select("OID = '" + Row + "'");
dr[0]["Value"] = Value.ToString("#,###.00");
this.BeginInvoke(new Action(() => { aData.AcceptChanges(); }));
}