Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For each textbox loop

Tags:

vb.net

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

like image 597
Lift Avatar asked Nov 22 '12 00:11

Lift


2 Answers

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
like image 149
Derek Tomes Avatar answered Sep 20 '22 17:09

Derek Tomes


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
like image 45
Colin Pear Avatar answered Sep 20 '22 17:09

Colin Pear