vbnewbie vbnewbie - 4 days ago 4
Vb.net Question

How to use for each in multiple control?

Im trying to clear all the field in textbox and uncheck all checkbox when the form on load

All my checkbox are inside TableLayoutPanel, but i have alot of TableLayoutPanel

Currently im using this method, but there is too many duplicate code

Private Sub ResetPage()

Dim ctrl As Control

For Each ctrl In tlp_userInfo.Controls
If TypeOf ctrl Is TextBox Then
ctrl.Text = Nothing
End If
If TypeOf ctrl Is ComboBox Then
ctrl.Text = Nothing
End If
Next

For Each ctrl In tlp_chkb1.Controls
If TypeOf ctrl Is CheckBox Then
DirectCast(ctrl, CheckBox).Checked = False
End If
Next

For Each ctrl In tlp_chkb2.Controls
If TypeOf ctrl Is CheckBox Then
DirectCast(ctrl, CheckBox).Checked = False
End If
Next

For Each ctrl In tlp_chkb3.Controls
If TypeOf ctrl Is CheckBox Then
DirectCast(ctrl, CheckBox).Checked = False
End If
Next

End Sub


is that any other way to uncheck all the checkbox in diffrent TableLayoutPanel?

Answer

Loop through all TableLayoutPanel in your form and loop through textboxes,checkboxes in each TableLayoutPanel

   For Each ctrl_tlo As Control In Me.Controls
      If TypeOf (ctrl_tlo) Is TableLayoutPanel Then
         For Each ctrl As Control In ctrl_tlo.Controls
             If TypeOf (ctrl) Is TextBox Then
                 ctrl.Text = ""
             ElseIf TypeOf (ctrl) Is CheckBox Then
                 DirectCast(ctrl, CheckBox).Checked = False
             End If
         Next
      End If
   Next
Comments