简体   繁体   中英

Set a DataGridView Cell Border Style to selected column only

I would like to do this border style on my 3rd column's cells.
Can anyone help me to accomplish this in DataGridView.

I'm talking about the selected part with red rectangle:

红色矩形

The borders which we can see in the specified column in the question are not cell borders. Cell borders are those dot lines between rows. So setting AdvancedBorderStyle in CellPaint method will not be much of help.

You need to perform some settings and do a bit custom painting.

These are some settings which helps you to achieve such style for rows and cells:

  • Setting Padding for the column
  • Setting row height
  • Setting cell border styles to none
  • Removing row headers
  • Handling CellPaint event:
    • Painting cell but contents.
    • Painting dotted border at top and bottom of rows.
    • Painting cell contents normally or like a text box for specific column.

Example

var specificColumn = 1;

dataGridView1.Columns[specificColumn].DefaultCellStyle.Padding = new Padding(10);
dataGridView1.RowTemplate.Height = 45;
dataGridView1.CellBorderStyle = DataGridViewCellBorderStyle.None;
dataGridView1.RowHeadersVisible = false;

dataGridView1.CellPainting += (obj, args) =>
{
    if (args.ColumnIndex < 0 || args.RowIndex < 0)
        return;
    args.Paint(args.CellBounds, DataGridViewPaintParts.All & 
        ~DataGridViewPaintParts.ContentForeground);
    var r = args.CellBounds;
    using (var pen = new Pen(Color.Black))
    {
        pen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot;
        args.Graphics.DrawLine(pen, r.Left, r.Top, r.Right, r.Top);
        args.Graphics.DrawLine(pen, r.Left, r.Bottom, r.Right, r.Bottom);
    }
    r.Inflate(-8, -8);
    if (args.ColumnIndex == specificColumn)
        TextBoxRenderer.DrawTextBox(args.Graphics, r, $"{args.FormattedValue}",
            args.CellStyle.Font, System.Windows.Forms.VisualStyles.TextBoxState.Normal);
    else
        args.Paint(args.CellBounds, DataGridViewPaintParts.ContentForeground);
    args.Handled = true;
};

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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