在datagridview中绘制单元格周围的边框

时间:2014-02-05 14:46:53

标签: vb.net winforms datagridview

我有datagridview这是一个例子:

enter image description here

我想在黄色周围绘制一个矩形,我有单元格索引,有人可以帮助我吗?

我将非常感激

1 个答案:

答案 0 :(得分:2)

您所做的就是设置Cell的Style.BackColor属性:

For i As Integer = 1 To 3
  dgv.Rows(2).Cells(i).Style.BackColor = Color.Yellow
Next

在单元格周围获取矩形的一种方法是使用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

结果:

enter image description here