Search code examples
vb.netdatagridviewcolorscelltextchanged

Backcolor not Coloring Entire Cell only Text


For the internet I pulled and amended some code to change the backcolor of the current cell in a datagridview upon editing the text. The problem is, the backcolor only seems to change within the cells text and not the entire cell (there seems to be a 3 pixel margin in the cell that has the original color). Below is the code I'm using:

Public Class Form1

Dim a, b As Integer
Dim myvalue As String

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
    a = 0
    Do While a < 10
        Me.DataGridView1.Rows.Add()
        a += 1
    Loop
End Sub

Private EditingControl As DataGridViewTextBoxEditingControl

Private Sub DataGridView1_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
    EditingControl = e.Control
    AddHandler EditingControl.TextChanged, AddressOf EditingControl_TextChanged
End Sub

Private Sub EditingControl_TextChanged(sender As Object, e As EventArgs)
    EditingControl.BackColor = Color.White
End Sub

Private Sub DataGridView1_CellEndEdit(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit
    If EditingControl IsNot Nothing Then
        RemoveHandler EditingControl.TextChanged, AddressOf EditingControl_TextChanged
    End If
    EditingControl = Nothing
End Sub
End Class

Does anybody know what I've done wrong with the code?


Solution

  • The EditingControl is put on a panel and has a 3 pixels margin.

    Colouring the parent panel solves your problem :

    Private Sub EditingControl_TextChanged(sender As Object, e As EventArgs)
        EditingControl.BackColor = Color.White
        EditingControl.Parent.BackColor = Color.White
    End Sub
    

    By the way, DataGridView class already has an EditingControl property.