在 C# DataGridView 中创建底部和右侧单元格边框

Creating bottom and right cell borders in C# DataGridView

我正在寻求帮助为我的 DataGridView 创建自定义边框。我正在寻找的是创建一种样式,其中 header 列单元格仅具有实心底部边框,而 header 行仅具有实心右边框。

我通过调整 this question 成功绘制了列 header 的边框。但是,我正在努力绘制 header 行的边框。

下图显示了我目前的情况。如您所见,header 列的边框为黑色实线。红线是我为 header 行绘制的,但我似乎无法让这条线延伸到 table 中的所有行。换句话说,如何让红线在所有行的 header 行单元格中绘制?

这是我当前使用的事件处理程序

private void TransitionTable_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
    if (e.RowIndex == -1 && e.ColumnIndex > -1){
        e.Handled = true;
        using (Brush b = new SolidBrush(activeTable.DefaultCellStyle.BackColor)){
            e.Graphics.FillRectangle(b, e.CellBounds);
        }

        using (Pen p = new Pen(Brushes.Black)){
             p.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid;
              e.Graphics.DrawLine(p, new Point(0, e.CellBounds.Bottom - 1), new Point(e.CellBounds.Right, e.CellBounds.Bottom - 1));

            //This `if` statement is what I've managed to get working, but I can't get it to draw the line on all rows.
            //It only draws in the first row
            if (e.ColumnIndex == 0)
            {
                Pen b = new Pen(Brushes.Red);
                e.Graphics.DrawLine(b, new Point(e.CellBounds.Right - 1, 0), new Point(e.CellBounds.Right - 1, e.CellBounds.Bottom - 1));
            }
        }
        e.PaintContent(e.ClipBounds);
    }
}

您的代码有两个问题:

1) 您从一个仅适用于列 header 行 (-1) 的条件开始。您将需要两个代码块,其中行和 column-headers 具有不同的条件,可能像这样:

private void TransitionTable_CellPainting(object sender, 
                                          DataGridViewCellPaintingEventArgs e)
{
    using (Brush b = new SolidBrush(TransitionTable.DefaultCellStyle.BackColor))
        e.Graphics.FillRectangle(b, e.CellBounds);

    e.PaintContent(e.ClipBounds);

    if (e.RowIndex == -1)  // column header
    {
        e.Graphics.DrawLine(Pens.Black, 0, e.CellBounds.Bottom - 1, 
                                        e.CellBounds.Right, e.CellBounds.Bottom - 1);
    }
    if (e.ColumnIndex == -1)  // row header (*)
    {
        e.Graphics.DrawLine(Pens.Red, e.CellBounds.Right - 1, 0, 
                                      e.CellBounds.Right - 1, e.CellBounds.Bottom - 1);
    }
    e.Handled = true;
}

或者您可以通过将整个块包裹在 or-condition 中来避免 owner-drawing 常规单元格,如下所示:

if (e.RowIndex == -1 || e.ColumnIndex = -1) 
{
     all the code above in here!
}

2) 您的代码和屏幕截图看起来确实 没有任何 RowHeaders,但是,并在 第一个数据列 中画线。如果这是您想要的,请忽略最后一条评论,只需将条件 (*) 更改为

    if (e.ColumnIndex == 0)