代码之家  ›  专栏  ›  技术社区  ›  Jared Harley

阻止窗体绘制的DataGridView CellFormatting事件

  •  3
  • Jared Harley  · 技术社区  · 15 年前

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

    我的单元格格式代码:

    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 http://img213.imageshack.us/img213/2430/menubar.jpg

    搜索前是顶部,搜索后是底部。直到我将鼠标移到菜单项所在的位置,菜单栏才会重新绘制,当我将鼠标移出菜单栏时,最后一个要突出显示的项将保持该状态。移动表单似乎会导致重新绘制,但问题仍然存在。

    评论 resultsGridView.CellFormatting DataGridView代码中的行完全修复了问题。

    我是不是把细胞漆错了,还是有别的事情需要处理?

    1 回复  |  直到 15 年前
        1
  •  1
  •   Henk Holterman    15 年前

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

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

    再看一眼,我不认为 therow.Cells["Sealed"] 会有用的。尝试一下 therow.Cells["dataGridViewTextBoxColumn2"] . 单元格索引依据 列名 不是 数据属性名称 .