Reputation: 145
I have a form that contains several Textboxes and Comboboxes. I have set active control's back color property to skyblue. I want to set the back color of all textboxes and comboboxes to white while they are not active.
Upvotes: 0
Views: 487
Reputation: 941437
There's a Right Way and a wrong way to do this. You are asking for the wrong way. The right way is to derive your own class from TextBox and override the OnEnter and OnLeave methods. Repeat for ComboBox.
But you ask for the wrong way and you are probably trying to add this feature too late so we'll have to slug it out by finding the controls back at runtime. Add a constructor to your form class and make it look like:
Public Sub New()
InitializeComponent()
FindControls(Me.Controls)
End Sub
Private Sub FindControls(ctls As Control.ControlCollection)
For Each ctl As Control In ctls
Dim match As Boolean
If TypeOf ctl Is TextBoxBase Then match = True
If TypeOf ctl Is ComboBox Then
Dim combo = DirectCast(ctl, ComboBox)
If combo.DropDownStyle <> ComboBoxStyle.DropDownList Then match = True
End If
If match Then
AddHandler ctl.Enter, AddressOf ControlEnter
AddHandler ctl.Leave, AddressOf ControlLeave
End If
FindControls(ctl.Controls)
Next
End Sub
Private controlColor As Color
Private Sub ControlEnter(sender As Object, e As EventArgs)
Dim ctl = DirectCast(sender, Control)
controlColor = ctl.BackColor
ctl.BackColor = Color.AliceBlue
End Sub
Private Sub ControlLeave(sender As Object, e As EventArgs)
Dim ctl = DirectCast(sender, Control)
ctl.BackColor = controlColor
End Sub
Upvotes: 1