سؤال

I'd like to know how to create a Class to change each textbox BackColor inside a Form. To be more Specific:

  1. When the textbox Is Empty, the textbox BackColor equals White.
  2. When the textbox Get focus, the textbox BackColor change.
  3. When the textbox have any text, the textbox BackColor change.
  4. When the textbox Lost focus, the textbox BackColor change.

At the moment, I'm doing it this way.

Private Sub tb_Login_Enter(sender As Object, e As EventArgs) Handles tb_Login.Enter
    tb_Login.BackColor = Color.LightCyan
End Sub

Private Sub tb_Login_Leave(sender As Object, e As EventArgs) Handles tb_Login.Leave
    If tb_Login.Text <> "" Then
        tb_Login.BackColor = Color.LightGreen
    Else
        tb_Login.BackColor = Color.White
    End If

But, I have many TextBox in my from, so, how can I create a Class for it?

Thanks

هل كانت مفيدة؟

المحلول

All you need to do is inherit from the TextBox control.

Public Class TextBoxEx
    Inherits TextBox

    Private Sub TextBoxEx_Enter(sender As Object, e As EventArgs) Handles Me.Enter
        Me.BackColor = Color.LightCyan
    End Sub

    Private Sub TextBoxEx_Leave(sender As Object, e As EventArgs) Handles Me.Leave
        If Me.Text <> "" Then
            Me.BackColor = Color.LightGreen
        Else
            Me.BackColor = Color.White
        End If
    End Sub
End Class

Build your project and then replace your TextBox controls with the new TextBoxEx control.

نصائح أخرى

You can create a class that has a collection of textbox controls. You can get this collection going through the Controls property of your Form or user control and verifying the type of the control. Internally the class must subscribe to the events you've listed, of the textbox controls collection. Finally, on the methods that handle the events you must write the logic that change the color accordingly. Remember that the handle events methods have the control that triggered the event on the first parameter.

I can go into more detail if you have more doubts.

Like in the movie...... ten years later......

Private Sub frmLogin_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    For Each tb As TextBox In Controls.OfType(Of TextBox)()
        AddHandler tb.Enter, Sub() tb.BackColor = Color.Red
        AddHandler tb.Leave, Sub() tb.BackColor = Color.White
    Next
End Sub

With this one there's no problem even with MaskedTextBox.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top