在非托管代码调用托管代码中的控件方法,常常会出现这个错误。
在控件所在的界面使用委托,在初始化的时候 delegateGrid = new DelegateGrid(GridRefresh);
private delegate void DelegateGrid(int channelId, string columnName, string columnValue);
DelegateGrid delegateGrid = null;
void GridRefresh(int channelId, string columnName, string columnValue)
{
for (int i = 0; i < dataGridViewX1.Rows.Count; i++)
{
if (dataGridViewX1.Rows[i].Cells["通道号"].Value.ToString() == channelId.ToString())
{
dataGridViewX1.Rows[i].Cells[columnName].Value = columnValue;
return;
}
}
}
public void OnGridRefresh(int channelId, string columnName, string columnValue)
{
if (null != delegateGrid)
{
if (this.InvokeRequired)
{
this.Invoke(delegateGrid, channelId, columnName, columnValue);
}
else
{
delegateGrid(channelId, columnName, columnValue);
}
}
}
在其他线程中调用 OnGridRefresh 这个公用方法。
转载于:https://www.cnblogs.com/todd/archive/2008/06/17/1223609.html
本文介绍了一种在非托管代码中调用托管代码控件方法的解决方案,通过使用委托来实现跨线程更新DataGridView控件的具体步骤。该方法有效地避免了因尝试从其他线程直接修改UI控件而引发的异常。
4469

被折叠的 条评论
为什么被折叠?



