Reputation: 528
I have a datagridview
this is an example:
I want to draw a rectangle around yellow color, I have the cells indexes, can someone help me?
I will be very grateful
Upvotes: 1
Views: 7290
Reputation: 81610
All you do is set the Cell's Style.BackColor property:
For i As Integer = 1 To 3
dgv.Rows(2).Cells(i).Style.BackColor = Color.Yellow
Next
One way to get a rectangle around the cells is to use the CellPainting event and see if it's yellow or not, then test the neighboring cells to determine whether or not to draw a border line:
Private Sub dgv_CellPainting(sender As Object, _
e As DataGridViewCellPaintingEventArgs) _
Handles dgv.CellPainting
If (e.CellStyle.BackColor.ToArgb = Color.Yellow.ToArgb) Then
e.Graphics.FillRectangle(Brushes.Yellow, e.CellBounds)
If (e.ColumnIndex = 0 OrElse _
dgv.Rows(e.RowIndex).Cells(e.ColumnIndex - 1).Style.BackColor.ToArgb <> Color.Yellow.ToArgb) Then
e.Graphics.DrawLine(Pens.Black, _
e.CellBounds.Left, e.CellBounds.Top, e.CellBounds.Left, e.CellBounds.Bottom)
End If
e.Graphics.DrawLine(Pens.Black, _
e.CellBounds.Left, e.CellBounds.Top, e.CellBounds.Right, e.CellBounds.Top)
e.Graphics.DrawLine(Pens.Black, _
e.CellBounds.Left, e.CellBounds.Bottom - 1, e.CellBounds.Right, e.CellBounds.Bottom - 1)
If (e.ColumnIndex = dgv.Rows.Count - 1 OrElse _
dgv.Rows(e.RowIndex).Cells(e.ColumnIndex + 1).Style.BackColor.ToArgb <> Color.Yellow.ToArgb) Then
e.Graphics.DrawLine(Pens.Black, _
e.CellBounds.Right - 1, e.CellBounds.Top, e.CellBounds.Right - 1, e.CellBounds.Bottom)
End If
e.Handled = True
End If
End Sub
Result:
Upvotes: 3