如何确定控件是复选框还是单选按钮?

时间:2011-12-08 18:56:41

标签: asp.net vb.net

我有一个if语句,需要检查传递的控件是复选框还是单选按钮

            If TypeOf (Control) Is CheckBox Then

                If count = 1 Then
                    text += Me.GetCheckBoxValueJQuerySyntax(Control.ClientID) & " + '~' + "
                Else
                    text += Me.GetCheckBoxValueJQuerySyntax(Control.ClientID) & "'~' + "
                End If

            End If
            If TypeOf (Control) Is RadioButton Then

                If CType(Control, RadioButton).GroupName <> "" Then

                    If Not Me._GroupNameArrayList.Contains(CType(Control, RadioButton).GroupName) Then

                        Me._GroupNameArrayList.Add(CType(Control, RadioButton).GroupName)

                        If count = 1 Then
                            text += Me.GetRadioValueJQuerySyntax(Control.ClientID) & " + '~' + "
                        Else
                            text += Me.GetRadioValueJQuerySyntax(Control.ClientID) & "'~' + "
                        End If
                    End If
                Else

                    If count = 1 Then
                        text += Me.GetRadioValueJQuerySyntax(Control.ClientID) & " + '~' + "
                    Else
                        text += Me.GetRadioValueJQuerySyntax(Control.ClientID) & "'~' + "
                    End If

                End If


            End If

由于checkbox和redio按钮派生自同一个类,因此失败,因此如何检查控件是复选框还是单选按钮

2 个答案:

答案 0 :(得分:3)

你很亲密; RadioButton来自CheckBox,因此他们都是技术上 CheckBox es。因此,在这种情况下,您可以翻转语句并使用Else If来获取您正在寻找的结果。

If TypeOf Control Is RadioButton Then
    ' The control is a RadioButton.
ElseIf TypeOf Control Is CheckBox Then
    ' The control is a CheckBox.
End If

答案 1 :(得分:0)

什么?除非这是asp.net特有的......

Private Sub Button3_Click(sender As System.Object, _
                          e As System.EventArgs) Handles Button3.Click

    Dim ctrl As Control = Me.GetNextControl(Me, True)
    Do Until ctrl Is Nothing
        If TypeOf ctrl Is RadioButton Then
            Debug.WriteLine("rb " & ctrl.Name)
        ElseIf TypeOf ctrl Is CheckBox Then
            Debug.WriteLine("cb " & ctrl.Name)
        End If

        'reverse check
        If TypeOf ctrl Is CheckBox Then
            Debug.WriteLine("cb " & ctrl.Name)
        ElseIf TypeOf ctrl Is RadioButton Then
            Debug.WriteLine("rb " & ctrl.Name)
        End If

        ctrl = Me.GetNextControl(ctrl, True)
    Loop

End Sub

看起来顺序没关系,但我没有用asp.net测试。