1

抱歉,如果我的问题太长,但我必须在提问之前解释一下。

我想在满足我设置的条件时更改单元格的文本颜色。

我还想在每 2 行中绘制水平线,在每 5 列中绘制垂直线。

我可以分别做这两个。问题是我不能同时得到它们。

如果我先更改文本,受影响单元格的边框就会消失。

如果我先绘制边框,文本颜色会变回黑色(默认)。

我必须更改单元格的文本颜色和边框颜色。

我的代码如下:

Private Sub GridBorderLine(ByVal e As System.Windows.Forms.DataGridViewCellPaintingEventArgs)
    'Declare Border Style and Border Color
    Dim vBStyle As ButtonBorderStyle = ButtonBorderStyle.Solid
    Dim vBColor As Color = Color.Black

    'Custom Row Border (Horizontal)
    If e.RowIndex Mod 2 = False AndAlso e.RowIndex > 0 Then
        e.Paint(e.CellBounds, DataGridViewPaintParts.All - DataGridViewPaintParts.ContentBackground)

        Dim H As Integer = 0
        ControlPaint.DrawBorder(e.Graphics, e.CellBounds, vBColor, 0, vBStyle, vBColor, 3, vBStyle, vBColor, 0, vBStyle, vBColor, 0, vBStyle)
        e.Handled = True
    End If

    'Custom Column Border (Vertical)
    If e.ColumnIndex Mod 5 = False AndAlso e.ColumnIndex > 0 Then
         e.Paint(e.CellBounds, DataGridViewPaintParts.All - DataGridViewPaintParts.ContentBackground)

        Dim W As Integer = 0
        If e.RowIndex Mod 2 = False And e.RowIndex > 0 Then W = 3 Else W = 0
        ControlPaint.DrawBorder(e.Graphics, e.CellBounds, vBColor, 3, vBStyle, vBColor, W, vBStyle, vBColor, 0, vBStyle, vBColor, 0, vBStyle)
        e.Handled = True
    End If

    'Custom Cell Color
    If e.FormattedValue.ToString.Contains(txt.Text) Then 
        CellColor(e)
    End If
End Sub

Private Sub CellColor(ByVal e As System.Windows.Forms.DataGridViewCellPaintingEventArgs)
    Dim vLength as Integer = txt.Text.Length
    e.Paint(e.CellBounds, DataGridViewPaintParts.All - DataGridViewPaintParts.ContentForeground)

    If e.FormattedValue.ToString = "" Then Exit Sub
    Dim vBeginning As String = e.FormattedValue.ToString.Substring(0, vLength)
    Dim vEnd As String = e.FormattedValue.ToString.Substring(vLength)

    Dim s As Size = TextRenderer.MeasureText(e.FormattedValue.ToString, vFont)
    Dim f As Size = TextRenderer.MeasureText(vBeginning, vFont)
    Dim b As Size = TextRenderer.MeasureText(vEnd, vFont)

    'Arrange Center Middle
    Dim w = e.CellBounds.X + ((e.CellBounds.Width - s.Width) / 2)
    Dim h = e.CellBounds.Y + ((e.CellBounds.Height - s.Height) / 2)

    Dim topLeft As New Point(w, h)
    Dim p As New Point(topLeft.X + (s.Width - b.Width), topLeft.Y)

   TextRenderer.DrawText(e.Graphics, vBeginning, vFont, topLeft, Color.Red)
    TextRenderer.DrawText(e.Graphics, vEnd, vFont, p, Color.Blue)

    e.Handled = True
End Sub
4

0 回答 0