C# 如何更改datagridview列分隔符颜色c winforms

C# 如何更改datagridview列分隔符颜色c winforms,c#,winforms,datagridview,C#,Winforms,Datagridview,首先,我尝试更改dataGridView1.BackgroundColor、dataGridView1.GridColor,但没有成功。。然后我尝试了dataGridView1.EnableHeadersVisualStyles=false dataGridView1.ColumnHeadersDefaultCellStyle.BackColor=Color.White,但没有任何效果 您需要处理CellPaint事件并使用所需颜色填充背景,例如与GridColor相同的颜色,然后通过将绘制区域

首先,我尝试更改dataGridView1.BackgroundColor、dataGridView1.GridColor,但没有成功。。然后我尝试了dataGridView1.EnableHeadersVisualStyles=false dataGridView1.ColumnHeadersDefaultCellStyle.BackColor=Color.White,但没有任何效果

您需要处理CellPaint事件并使用所需颜色填充背景,例如与GridColor相同的颜色,然后通过将绘制区域限制为矩形(不包括分隔线)来执行其余的绘制:

private void DataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
    if (e.RowIndex == -1)
    {
        var dgv = (DataGridView)sender;
        var r = e.CellBounds;
        var w = 0;
        if (e.ColumnIndex > -1)
        {
            w = dgv.Columns[e.ColumnIndex].DividerWidth;
            r.Width = r.Width - w;
        }
        e.Graphics.SetClip(r);
        e.Paint(r, DataGridViewPaintParts.All);
        e.Graphics.SetClip(e.CellBounds);
        if (w > 0)
        {
            r = new Rectangle(r.Right - 1, r.Top, w + 1, r.Height);
            using (var brush = new SolidBrush(dgv.GridColor))
                e.Graphics.FillRectangle(brush, r);
        }
        e.Handled = true;
    }
}
例如,如果将列的DividerWidth设置为10,并将GridColor设置为Color.Red,则使用上述代码可以得到以下结果:


这可能会对你有所帮助:当你试图改变它的颜色时,它会让人困惑,但很重要。不要在类构造函数public Form1中更改它,但在它的load方法public void Form1\u load中我知道更改颜色在类构造函数中不起作用,这是一个常见的错误,但我从未使用过分隔符,所以我不知道这是否是您的问题不客气:请确保使用更新版本的代码。