【问题标题】:Paint a rectangle on the selected cell in Datagrid在 Datagrid 中的选定单元格上绘制一个矩形
【发布时间】:2012-11-11 12:29:26
【问题描述】:

我的项目中有一个DataGrid,选择模式为:FullRowSelect。如何在单击的单元格上绘制矩形(如ListView 中选定单元格上的矩形)?或者换个颜色?

【问题讨论】:

    标签: c# winforms datagrid


    【解决方案1】:

    我通过处理 CellFormatting 事件改变了 DataGridViews 的颜色。我这样做是为了突出显示错误的行,或者突出显示特定的列;

    在我的表单初始化方法中,我有类似的东西;

    dgvData.CellFormatting += 
                new DataGridViewCellFormattingEventHandler(dgvData_CellFormatting);
    

    负责格式化的方法如下;

            private void dgvData_CellFormatting(object sender,
                                        DataGridViewCellFormattingEventArgs e)
            {
                bool inError = false;
    
                // Highlight the row as red if we're in error displaying mode
                if (e.RowIndex >= 0 && fileErrors != null && DisplayErrors)
                {
                    // Add +1 to e.rowindex as errors are using a 1-based index
                    var dataErrors = (from err in fileErrors
                                      where err.LineNumberInError == (e.RowIndex +1)
                                      select err).FirstOrDefault();
                    if (dataErrors != null)
                    {
                        e.CellStyle.BackColor = Color.Red;
                        inError = true;
                    }
                }
    
                // Set all the rows in a column to a colour, depending on it's mapping.
                Color colourToSet = GetBackgroundColourForColumn(dgvData.Columns[e.ColumnIndex].Name);
                if (colourToSet != null && !inError)
                    e.CellStyle.BackColor = colourToSet;
            } 
    

    为了对特定单元格执行此操作,您可能还需要处理控件上的 MouseUp 事件,然后使用数据网格视图的 HitTestInfo 来确定实际点击的是哪个单元格。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多