动态清除控件的值

时间:2016-05-04 16:04:41

标签: vb.net visual-studio

我想知道是否存在动态清除Panel动态值的算法,而无需手动完成。如果可能的话递归。我脑子里有这个想法,但它没有明显的编译。

    Private Sub ClearAll(ByRef panel As Control)

    For Each objControl As Control In panel.Controls

        If (TypeOf objControl Is Panel) Then
            ClearAll(objControl)
        End If

        If (TypeOf objControl Is CheckBox Or TypeOf objControl Is RadioButton) Then
            objControl.Checked = False
        End If

        If (TypeOf objControl Is TextBox) Then
            objControl.Clear()
        End If

    Next

End Sub

2 个答案:

答案 0 :(得分:0)

如果您有TabControl或GroupeControle,可以尝试这样做以便添加许多区域作为示例:

 Public Shared Sub ClearChamps(ByVal myObject As Control)


        '#Region "Controls XtraTabControl"

        '#End Region

        '#Region "Controls XtraTabPage"

        ' #Region "Controls GroupControl"
        '****les controles de la GroupControl
        If TypeOf myObject Is Control Then
            Dim cont2 As Control = DirectCast(myObject, Control)

            For Each myObject1 As [Object] In cont2.Controls

                'If TypeOf myObject1 Is LookUpEdit Then
                '    '(myObject1 as LookUpEdit).ClosePopup() ;

                '    TryCast(myObject1, LookUpEdit).EditValue = Nothing
                If TypeOf myObject1 Is TextBox Then
                    TryCast(myObject1, TextBox).Text = String.Empty
                End If
                If TypeOf myObject1 Is DataGridView Then
                    myObject1.Rows.Clear()
                End If
                If (TypeOf myObject1 Is CheckBox Or TypeOf myObject1 Is RadioButton) Then
                    myObject1.Checked = False
                End If
            Next
        End If
        '  #End Region
        '#Region "Groupbox"
        '****les controles de la GroupControl

    End Sub

您可以将ClearChamps(ByVal myObject As Form)用于表单中所有控件的目标

答案 1 :(得分:0)

你关闭了!

  • 当你递归时,你不必检查类型,所有Control对象都有.controls并且检查它们并不会受到伤害(速度增益不值得代码臃肿) )

  • 在VB中使用CType。

然后你就完成了! (为清楚起见:将变量'面板重命名为' ctl'等等;它现在不会永远是一个面板,可能是一个组合框)

Private Sub ClearAll(ByRef panel As Control)

  For Each objControl As Control In panel.Controls

    ClearAll(objControl)

    If TypeOf objControl Is Checkbox then
        ctype(objControl,Checkbox).Checked = False
    End If
    If TypeOf objControl Is RadioButton then
        ctype(objControl,RadioButton).Checked = False
    End If

    If TypeOf objControl Is TextBox Then
        ctype(objControl,textbox).Clear()
    End If

    ' etc ... e.g., if Listbox, ctype(...).SelectedIndex=-1, then if Dropdown...

  Next

End Sub

理想情况下,winforms控件会实现简单的接口,允许控制它们共有的东西。

  • 所有控件 - 使用.Reset方法实现ISetToDefault,清除文本框,复选框,列表框等。
  • list / combo:IHaveListItems,在combo / listbox上具有.List的所有属性,允许操作列表为单一类型(在wf中,两者是令人沮丧的不同类型!)
  • text / combo:带有.Text属性的IHaveUserEnteredText
  • 所有控件 - 带有.Value属性的IHaveValue作为字符串(将是布尔的.ToString或等)。
  • groupbox / check / option - 带有.Caption的IHaveCaption,你明白了。

但我们现在不能重写winforms ......