【问题标题】:DataGridView CellFormatting event preventing form paintingDataGridView CellFormatting 事件阻止表单绘制
【发布时间】:2010-12-22 04:09:06
【问题描述】:

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

我的表单有一个自定义DataGridView(双缓冲以防止在我的单元格格式化事件期间闪烁,as seen here)。当我执行数据库搜索时,我将结果数据集绑定到 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;
    }
}

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

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

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

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

【问题讨论】:

    标签: c# winforms events datagridview paint


    【解决方案1】:

    您可能在此事件中引发了异常。我不确定如何定义处理,但第一步是用 try catch 包围代码。

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

    再看一遍,我认为therow.Cells["Sealed"] 行不通。试试therow.Cells["dataGridViewTextBoxColumn2"] 之类的东西。单元格按列名而非DataPropertyName编制索引。

    【讨论】:

    • “密封”部分不是数据属性,而是我数据库中的布尔条件。我正在开发的程序会搜索姓名,并可以显示我们在部门的案件档案是否已被密封。
    • 没有要捕获的异常。我在格式化事件的开头添加了Systems.Diagnotics.Trace.WriteLine("start"),它运行了很多,即使在显示单元格之后也没有其他事情发生。
    • 但是“密封”是 Dgv Column 对象的名称吗?
    • 我认为你应该设置e.CellStyle.BackColor,而不是theRow.DefaultCellStyle.BackColor
    • 你明白了 - 改变细胞的绘制方式是诀窍。更改为 e.CellStyle.BackColor 可以修复它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-16
    • 1970-01-01
    相关资源
    最近更新 更多