CellFormatting事件导致.NET 4.5应用程序上的呈现不稳定
本文关键字:程序上 应用程序 不稳定 应用 事件 NET CellFormatting | 更新日期: 2023-09-27 18:29:29
在一个简单的.NET WinForm中,我有一个datagridview
,它正在根据单元格的值进行颜色绘制。代码正在工作,但呈现的形式"不稳定"(当计算机不断需要重新绘制而无法跟上时的样子)。我想知道我是否可以做些什么来消除这种情况,或者我的代码是否有问题。非常感谢您的建议。
private void gvPhoneQueue_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
try
{
if (gvPhoneQueue.Columns[e.ColumnIndex].HeaderText == "CallsWaiting")
{
string convertedVal = e.Value.ToString();
if (Convert.ToInt32(convertedVal) > _greenTolerance)
{
gvPhoneQueue.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Green;
}
if (Convert.ToInt32(convertedVal) > _yellowTolerance)
{
gvPhoneQueue.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Yellow;
}
if (Convert.ToInt32(convertedVal) > _redTolerance)
{
gvPhoneQueue.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;
}
}
}
catch (System.Exception ex)
{
LogEvent("Error" _+ ex);
}
}
在这种情况下,我已经看到了一些关于DataGridView
性能问题的线程(使用CellFormatting
、CellPainting
…)。当处理大量数据时,这可能是"已知问题"。
可以肯定的是,您应该避免在CellFormating
事件中做一些过于复杂的事情。我看不出你的代码有什么问题,但它似乎没有得到优化:
-
您使用3倍
Convert.ToInt32(convertedVal)
:您应该存储值,而不是转换3倍字符串值。如果您使用的是Try Cath
块,由于可能的转换错误,您可以使用int32.TryParse
方法。 -
我猜颜色不能同时是红色、黄色或绿色,_redTolence是最高值因此,您应该先测试最高值,然后再测试其他值,然后尽快退出该方法,因此,如果不需要,请不要每次评估3个
if
语句。在VB.Net中,我建议使用ElseIf
语句,但它在C#中不存在。在这种情况下,使用return
也是一样的。[编辑我在C#中的错误else if
等于VB.Net].中的ElseIf
可能的优化:
private void gvPhoneQueue_CellFormatting(object sender, System.Windows.Forms.DataGridViewCellFormattingEventArgs e)
{
if (gvPhoneQueue.Columns(e.ColumnIndex).HeaderText == "CallsWaiting") {
int convertVal = 0;
if (int.TryParse(e.Value.ToString, convertVal)) {
if (convertVal > _redTolerance) {
gvPhoneQueue.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.Red;
} else if (convertVal > _yellowTolerance) {
gvPhoneQueue.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.Yellow;
} else if (convertVal > _greenTolerance) {
gvPhoneQueue.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.Green;
}
} else {
//can't convert e.value
}
}
}