繁体   English   中英

如何在Datagridview中设置行/列标题单元格的背景色-C#WinForm

[英]How to set the back color of the row / column header cell in a datagridview - c# winform

我想设置datagridview的行标题和列标题相交单元格的背景色。 我尝试了下面的代码,但是它引发了一个例外,该数字应为非负数。

DataGridViewCell cell = dgview.Rows[-1].Cells[-1];
cell.Style.BackColor = Color.Red;

我要设置颜色,如下图所示

在此处输入图片说明

我还参考了下面的文章,但是它显示了如何设置整个列标题的颜色。 但是我的要求是设置单个单元格的颜色-行-列标题交集单元格。

如何对变化最显色的-的winform-datagridview的报头

任何帮助深表感谢。 谢谢。

问候,

维奈

将当前的ColumnHeadersDefaultCellStyle存储在变量中。

将ColumnHeadersDefaultCellStyle设置为所需的拐角位置。

然后将所有列标题更改为您希望第0列...回到旧样式的方式。

下面是将表单称为“ MyForm”的示例。 本示例显示MyForm的默认构造函数。

例:

    public MyForm()
    {
        InitializeComponent();

        // insert code here to add columns  ...
        // ...
        // ...
        // ...

        DataGridViewCellStyle oldDefault = dgview.ColumnHeadersDefaultCellStyle.Clone();

        dgview.ColumnHeadersDefaultCellStyle.BackColor = Color.Red;

        foreach (DataGridViewColumn item in dgview.Columns)
        {
            item.HeaderCell.Style = oldDefault;
        }
    }
    private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
    {
        if (e.RowIndex == -1 && e.ColumnIndex ==  -1)

        {
            using (Brush gridBrush = new SolidBrush(this.dataGridView1.GridColor))
            {
                using (Brush backColorBrush = new SolidBrush(Color.Red))
                {
                    using (Pen gridLinePen = new Pen(gridBrush))
                    {
                        // Clear cell 
                        e.Graphics.FillRectangle(backColorBrush, e.CellBounds);
                        //Bottom line drawing
                        e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left, e.CellBounds.Bottom-1 , e.CellBounds.Right, e.CellBounds.Bottom-1);
                        e.Handled = true;
                    }
                }
            }
        }

这有点麻烦,但是可以使用设计器(如果使用VS)在DataGridView内添加一个PictureBox并初始化其属性,例如:

pictureBox1.BackColor = Color.Red;
pictureBox1.Width = dgView.RowHeadersWidth;
pictureBox1.Height = dgView.ColumnHeadersHeight;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM