Tengo un formulario con un botón "Borrar".VB.NET - Iteración a través de controles en un objeto contenedor
Cuando el usuario hace clic en "Borrar", quiero borrar el valor de todos los elementos visibles en el formulario. En el caso de los controles de fecha, quiero restablecerlos a la fecha actual.
Todos mis controles están en un Panel.
En este momento, estoy haciendo esto con el siguiente código. ¿Hay una manera más fácil que verificar manualmente para cada tipo de control? Este método parece excesivamente difícil de manejar.
Para empeorar las cosas, con el fin de eliminar recursivamente los controles dentro de los sub-contenedores (es decir, un cuadro de grupo dentro del panel) tengo que repetir todo el monstruo con una versión "GroupBox" sobrecargada.
Editar: Gracias a sus sugerencias, el siguiente código se ve muy simplificado.
Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click
'User clicks Clear, so clear all the controls within this panel
ClearAllControls(panMid, True) 'True indicates that yes, i want to recurse through sub-containers
End Sub
ClearAllControls(ByRef container As Panel, Optional Recurse As Boolean = True)
'Clear all of the controls within the container object
'If "Recurse" is true, then also clear controls within any sub-containers
Dim ctrl As Control
For Each ctrl In container.Controls
If (ctrl.GetType() Is GetType(TextBox)) Then
Dim txt As TextBox = CType(ctrl, TextBox)
txt.Text = ""
End If
If (ctrl.GetType() Is GetType(CheckBox)) Then
Dim chkbx As CheckBox = CType(ctrl, CheckBox)
chkbx.Checked = False
End If
If (ctrl.GetType() Is GetType(ComboBox)) Then
Dim cbobx As ComboBox = CType(ctrl, ComboBox)
cbobx.SelectedIndex = -1
End If
If (ctrl.GetType() Is GetType(DateTimePicker)) Then
Dim dtp As DateTimePicker = CType(ctrl, DateTimePicker)
dtp.Value = Now()
End If
If Recurse Then
If (ctrl.GetType() Is GetType(Panel)) Then
Dim pnl As Panel = CType(ctrl, Panel)
ClearAllControls(pnl, Recurse)
End If
If ctrl.GetType() Is GetType(GroupBox) Then
Dim grbx As GroupBox = CType(ctrl, GroupBox)
ClearAllControls(grbx, Recurse)
End If
End If
Next
End Sub
@Theraccoonbear: Me gusta tu sugerencia, pero cuando cambio la declaración a este:
Private Sub ClearAllControls(ByRef controls As ControlCollection, Optional ByVal Recurse As Boolean = True)
Entonces esta línea me da "No se puede convertir objeto de tipo 'ControlCollection' escribir ' ControlCollection '. ":
ClearAllControls(panMid.Controls)
llamando a mehod: raz (Me.Controls) – user3692282
Trate de no publicar soluciones de solo código. – NathanOliver
bien, pero, creo que esta es una solución para la pregunta anterior, ¿no? – user3692282