I'm trying to make a foreach loop that checks every TextBox in a panel and changes BackColor if its Text is nothing. I've tried the following:
Dim c As TextBox
For Each c In Panel1.Controls
if c.Text = "" Then
c.BackColor = Color.LightYellow
End If
Next
but I'm getting the error:
Unable to cast object of type System.Windows.Forms.Label to type System.windows.forms.textbox
Try this. It'll put the color back when you enter data as well
For Each c As Control In Panel1.Controls
If TypeOf c Is TextBox Then
If c.Text = "" Then
c.BackColor = Color.LightYellow
Else
c.BackColor = System.Drawing.SystemColors.Window
End If
End If
Next
There is also a different way to do this which involves creating an inherited TextBox control and using that on your form:
Public Class TextBoxCompulsory
Inherits TextBox
Overrides Property BackColor() As Color
Get
If MyBase.Text = "" Then
Return Color.LightYellow
Else
Return DirectCast(System.Drawing.SystemColors.Window, Color)
End If
End Get
Set(ByVal value As Color)
End Set
End Property
End Class
You might try something like this instead:
Dim ctrl As Control
For Each ctrl In Panel1.Controls
If (ctrl.GetType() Is GetType(TextBox)) Then
Dim txt As TextBox = CType(ctrl, TextBox)
txt.BackColor = Color.LightYellow
End If
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With