Share via


How can I change the Background Color of a TextBox programmatically in Visual Basic

Question

Tuesday, June 7, 2016 2:50 AM

I have a TextBox that I would like to change the Background color to a different color than on the designer. Could you show me the code that could handle this?  I want to just change the text in the TextBox and automatically change the Background color when the text is changed.  Thank you.

 

All replies (1)

Tuesday, June 7, 2016 4:46 AM âś…Answered | 1 vote

Handle the TextChanged even, and assign the colour to BackColor property. For example, if your textbox is called TextBox1, and you want to apply a green background when the text contains more than three characters, then paste this fragment to your code; (press <F7> if you are in Form Designer):

Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged

    If TextBox1.TextLength > 3 Then
        TextBox1.BackColor = Color.Green
    Else
        TextBox1.BackColor = SystemColors.Window
    End If

End Sub