6

I need to programming change the border color of some cells in the CellFormatting event. Can the board color of an individual cell be changed?

1

2 Answers 2

11

You can draw a rectangle. In this example I put a red boder on the selected cells.

private void dataGridView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
    if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
    {
        if (dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected == true)
        {
            e.Paint(e.CellBounds, DataGridViewPaintParts.All & ~DataGridViewPaintParts.Border);
            using (Pen p = new Pen(Color.Red, 1))
            {
                Rectangle rect = e.CellBounds;
                rect.Width -= 2;
                rect.Height -= 2;
                e.Graphics.DrawRectangle(p, rect);
            }
            e.Handled = true;
        }
    }
}
3
  • This example works only if the cell is selected. What if I need to create several rectangles?
    – Doro
    Nov 6, 2014 at 7:32
  • @doro You can just change the conditional: selected == true Nov 7, 2014 at 22:55
  • How to apply the same effect to RowHeightChanged and ColumnWidthChanged events, for example?
    – Trowa
    Aug 15, 2017 at 12:52
1

MSDN describes a method where you can inherit from the DataGridView to override the default border styles: DataGridViewAdvancedBorderStyle Class

The painting method above is simpler, though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.