DataGridView的CellFormatting事件阻止了窗体绘制

4

我在使用C#、Winforms和.Net 3.5。

我的窗体有一个自定义的DataGridView(双缓冲以避免在单元格格式化事件期间出现闪烁,如此处所示)。当我执行数据库搜索时,我将结果数据集绑定到datagridview上。

我处理CellFormatting事件来根据它们的数据为行涂上不同的颜色。

我的DataGridView代码:

resultsGridView.DataSource = results.DefaultViewManager.DataSet.Tables[0];
resultsGridView.AlternatingRowsDefaultCellStyle.BackColor = Color.AliceBlue;
resultsGridView.BorderStyle = BorderStyle.Fixed3D;
resultsGridView.CellFormatting += new DataGridViewCellFormattingEventHandler(resultsGridView_CellFormatting);

我的 CellFormatting 代码:

void resultsGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    int rowIndex = e.RowIndex;
    DataGridViewRow therow = resultsGridView.Rows[rowIndex];
    if ((bool)therow.Cells["Sealed"].Value == true)
    {
        therow.DefaultCellStyle.BackColor = Color.Pink;
    }
    if (therow.Cells["Database"].Value as string == "PNG")
    {
        therow.DefaultCellStyle.BackColor = Color.LightGreen;
    }
}

除了在处理单元格式时,整个表格的绘制事件好像被关闭了,其他都运行良好。文本框中的光标停止闪烁,窗体的菜单栏看起来像这样:Menu bar picture 在搜索之前是上方,搜索之后是下方。菜单栏不会重新绘制,直到我鼠标移到菜单项所在位置,然后移开鼠标时,最后一个高亮显示的项目仍保持那种状态。似乎移动窗体会导致其重新绘制,但问题仍然存在。在 datagridview 代码中注释掉 resultsGridView.CellFormatting 行完全解决了该问题。我是否错误地绘制了单元格,或者还需要处理其他内容?
1个回答

1

你可能在这个事件中引发了一个异常。我不确定处理方式如何定义,但将代码用try catch包围起来是第一步。

try 
{
   int rowIndex = e.RowIndex;
   ....   
}
catch(Exception ex)
{
    System.Diagnostics.Trace.Error(ex.message);
}

仔细看了一下,我认为therow.Cells["Sealed"]不会起作用。尝试使用therow.Cells["dataGridViewTextBoxColumn2"]之类的东西。Cells是按列名称而不是DataPropertyName索引的。

“Sealed” 部分并不是数据属性,而是我数据库中的布尔条件。我正在开发的程序可以根据名称进行搜索,并显示我们部门的案件文件是否已经被封存。 - Jared Harley
没有异常需要捕获。我在格式化事件的开头添加了Systems.Diagnotics.Trace.WriteLine("start"),它一直在运行,即使单元格已经显示并且没有其他操作正在进行。 - Jared Harley
2
我认为您应该设置 e.CellStyle.BackColor,而不是 theRow.DefaultCellStyle.BackColor - H H
你做到了 - 改变单元格的绘制方式是关键。将其更改为 e.CellStyle.BackColor 可以解决问题。 - Jared Harley
也许你应该再读一遍关于Sealed的部分 - 数据库名称在这里不重要,它是关于组件的。 - H H
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接