For each cycle of the text field

I am trying to make a foreach loop that checks every TextBox in a panel and modifies the BackColor if its text is nothing. I 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 get an error:

Cannot apply an object of type System.Windows.Forms.Label to type System.windows.forms.textbox

+7
source share
3 answers

Instead, you can try something like this:

  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 
+8
source

Assuming there are no nested controls:

 For Each c As TextBox In Panel1.Controls.OfType(Of TextBox)() If c.Text = String.Empty Then c.BackColor = Color.LightYellow Next 
+13
source

Try it. It will also bring the color back when entering data.

  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 another way to do this, which involves creating an inherited TextBox control and using it in 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 
+2
source

All Articles