【问题标题】:How to check if a radiobutton is checked in a group如何检查组中是否选中了单选按钮
【发布时间】:2011-03-28 09:46:03
【问题描述】:

我有一组单选按钮,每组范围从 5 到 27 个单选按钮。如果选中了组中的任何单选按钮,我将 1 存储在 db 中,否则我存储 0。现在我正在使用 if 循环检查每个单选按钮,以查看它们是否被选中并设置数据库值。我也在尝试使用下面的代码。有没有更好/更好的方法来检查它们是否被检查?

当前代码:

'rname is radiobutton prefix for a given group
'cnt is number of radiobuttons in the group

Private Function RadioIsChecked(ByVal rname As String, ByVal cnt As Integer) As Integer
    Dim retval As Integer = 0
    For i = 0 To cnt - 1
        Dim rdbName As String = rname & i
        Dim rdb As New RadioButton()
        rdb = CType(Me.Page.FindControl(rdbName), RadioButton)
        If rdb.Checked Then
            retval = 1
        End If
    Next
    Return retval
End Function

注意:我不能使用单选按钮列表。我知道这可以使用它轻松实现,但我想获得单选按钮的解决方案

【问题讨论】:

    标签: asp.net .net vb.net radio-button


    【解决方案1】:

    【讨论】:

      【解决方案2】:

      无论哪种方式,都取决于您。
      只有在找到选中的项目后退出迭代,才能获得所需的性能提升。

      您可以如下修改迭代:

      For i = 0 To cnt - 1
          Dim rdbName As String = rname & i
          Dim rdb As New RadioButton()
          rdb = CType(Me.Page.FindControl(rdbName), RadioButton)
          If rdb.Checked Then
              retval = 1
              Exit For
          End If
      Next
      

      【讨论】:

        【解决方案3】:

        您还可以使用Request.Form("GroupNameGoesHere") 获取该组中当前选定单选按钮的值(如果不存在,则为空字符串)。

        【讨论】:

          【解决方案4】:

          改为将其设为 RadioButtonList。然后您可以简单地检查列表的“SelectedItem”属性。

          查看http://www.startvbdotnet.com/aspsite/controls/rblist.aspx 的示例。

          【讨论】:

            【解决方案5】:

            如果你使用前面提到的单选按钮列表,你可以做这样的事情。测试是否选择了某些东西。

            <asp:RadioButtonList runat="server" ID="rbList">
                  <asp:ListItem Text="Radio 1" />
                  <asp:ListItem Text="Radio 2" />
                  <asp:ListItem Text="Radio 3" />
            </asp:RadioButtonList>
            
            
            rbList.SelectedIndex > -1;
            

            【讨论】:

              猜你喜欢
              • 2016-09-26
              • 2012-03-07
              • 2021-10-21
              • 1970-01-01
              • 2017-07-24
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多