正在更改另一个线程中的DataGridViewRow属性
本文关键字:DataGridViewRow 属性 线程 另一个 | 更新日期: 2023-09-27 17:47:49
好的,所以我在后台线程中将DataGridView绑定到BindingSource,而一个小的"Please Wait"模型窗口可以让用户保持娱乐。没问题。
但是,我需要根据行的databounditemtype更改一些行的背景颜色。像这样:
for (int i = 0; i < dgItemMaster.Rows.Count; i++)
{
if (dgItemMaster.Rows[i].DataBoundItem.GetType().Name == "Package")
{
dgItemMaster.Rows[i].DefaultCellStyle.BackColor = Color.PowderBlue;
}
}
从程序上讲,我可以做到这一点,但它有足够的行,可以在迭代行时锁定GUI。我正在寻找处理这种情况的最佳方法。
这就是我现在正在做的:
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
dgItemMaster.DataSource = products;
dgItemMaster.BeginInvoke((Action)(() =>
{
for (int i = 0; i < dgItemMaster.Rows.Count; i++)
{
if (dgItemMaster.Rows[i].DataBoundItem.GetType().Name == "Package")
{
dgItemMaster.Rows[i].DefaultCellStyle.BackColor = Color.PowderBlue;
}
else if (dgItemMaster.Rows[i].DataBoundItem.GetType().Name == "PackageKit")
{
dgItemMaster.Rows[i].DefaultCellStyle.BackColor = Color.Pink;
}
}
}));
}
这里的数据量是多少?对于它来说,挂起UI必须是不平凡的。一个极端的答案是切换到虚拟模式,但这是一项艰巨的工作。
如果你只是不想挂起UI,也许只需立即执行前x(20?50?)行,然后批量执行其余行——本质上是模仿DoEvents
,只是没有DoEvents
的代码气味。。。
(未经测试)
int startIndex = 0;
Action action = null;
action = () =>
{ // only processes a batch of 50 rows, then calls BeginInvoke
// to schedule the next batch
int endIndex = startIndex + 50;
if (endIndex > dgItemMaster.Rows.Count) endIndex = dgItemMaster.Rows.Count;
if (startIndex > endIndex)
{
for (int i = startIndex; i < endIndex; i++)
{
// process row i
}
startIndex = endIndex;
this.BeginInvoke(action); // next iteration
}
};
// kick it off
this.BeginInvoke(action);
我会尝试在RowAdded事件中运行更改背景颜色的代码,这将在添加到网格时为每一行触发,无需再次迭代整个列表。
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.rowsadded.aspx
祝你好运。