在Datagrid中的所选单元格上绘制一个矩形 [英] Paint a rectangle on the selected cell in Datagrid

查看:161
本文介绍了在Datagrid中的所选单元格上绘制一个矩形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a DataGrid in my project with the selection mode: FullRowSelect. How can I paint a rectangle (like a rectangle on selected cell in ListView) on clicked cell? Or change the color maybe?

推荐答案

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

I've change colour of DataGridViews by handling the CellFormatting event. I do this for either highlighting rows that are in error, or highlighting specific columns;

在我的表单init方法中,我有一些像

In my form init method, I have something like;

dgvData.CellFormatting += 
            new DataGridViewCellFormattingEventHandler(dgvData_CellFormatting);

,负责格式的方法如下:

and the method responsible for the formatting is as follows;

        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来计算实际打击的单元格。

In order to do this for a specific cell, you may also need to handle the MouseUp event on the control and then use the HitTestInfo of the data grid view to work out which cell the hit was actually on.

这篇关于在Datagrid中的所选单元格上绘制一个矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆