vb.net 在datagridview中的单元格周围绘制边框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21580439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Draw border around cells in datagridview
提问by Silvia Parfeni
I have a datagridviewthis is an example:
我有一个datagridview这是一个例子:


I want to draw a rectangle around yellow color, I have the cells indexes, can someone help me?
我想在黄色周围画一个矩形,我有单元格索引,有人可以帮我吗?
I will be very grateful
我将不胜感激
回答by LarsTech
All you do is set the Cell's Style.BackColor property:
你所做的就是设置 Cell 的 Style.BackColor 属性:
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:
在单元格周围获得矩形的一种方法是使用 CellPainting 事件并查看它是否为黄色,然后测试相邻的单元格以确定是否绘制边界线:
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:
结果:



