Lift
Lift

Reputation: 546

For each textbox loop

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

Upvotes: 10

Views: 50380

Answers (3)

Derek Tomes
Derek Tomes

Reputation: 4007

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

Upvotes: 3

Victor Zakharov
Victor Zakharov

Reputation: 26414

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

Upvotes: 18

Colin Pear
Colin Pear

Reputation: 3100

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

Upvotes: 16

Related Questions