在C#DataGridView

时间:2016-07-28 11:12:12

标签: c# winforms datagridview border

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

我已成功通过调整this question来成功绘制列标题边框。但是,我正在努力绘制行标题边框。

下图显示了到目前为止我所拥有的内容。如您所见,列标题的边框为黑色实线。红线是我设法为行标题绘制的,但我似乎无法使该行扩展到表中的所有行。换句话说,如何在所有行的行标题单元格中绘制红线?

current border example

这是我正在使用的事件处理程序

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 个答案:

答案 0 :(得分:2)

您的代码有两个问题:

1)您的条件仅适用于列标题行(-1)。您将需要两个代码块,其中包含行标题和列标题的单独条件,可能是这样的:

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中来避免所有者绘制常规单元格:

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

2)您的代码和屏幕截图确实看起来好像没有拥有任何RowHeaders,并且在< strong>第一个数据列。如果这是您想要的,请忽略最后一个注释,只需将条件( * )更改为

    if (e.ColumnIndex == 0)

enter image description here