我正在使用 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);

我的单元格格式代码:

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;
    }
}

一切都很好,除了当我处理 CellFormatting 时,整个表单的 Paint 事件似乎被关闭。光标在文本框中停止闪烁,窗体的菜单条如下所示:

Menu bar picture

顶部是搜索之前,底部是搜索之后。除非我将鼠标悬停在菜单项所在的位置,否则菜单栏不会重绘,然后当我将鼠标移出菜单栏时,要突出显示的最后一个项目将保持这种状态。移动表单似乎会导致它重新绘制,但问题仍然存在。

注释掉 resultsGridView.CellFormatting datagridview 代码中的行完全解决了问题。

我是否画错了单元格,或者我还需要处理其他问题吗?

有帮助吗?

解决方案

你可能会导致此事件中的异常。我不知道该处理是如何定义的,而是围绕着一个尝试捕捉的代码将是第一步。

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

在第二次看,我不认为therow.Cells["Sealed"]会工作。尝试类似therow.Cells["dataGridViewTextBoxColumn2"]。细胞是通过<强>色谱柱名称下,索引不的 DataPropertyName

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top