如何检查组中是否检查了单选按钮
问题描述:
我有一组单选按钮,每个组的范围是5 - 27个单选按钮。如果组中的任何一个单选按钮被选中,我在db中存储1,否则我存储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
注:我不能用单选按钮列表。我知道这很容易使用这个来实现,但是我想要得到的单选按钮
答
无论哪种方式,这取决于你。
只有在找到选中的项目后退出迭代时,才会获得所需的性能提升。
如下您可以修改迭代:
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
答
的解决方案是有可能让你使用一个单选按钮列表
见:http://www.java2s.com/Code/ASP/Asp-Control/GetselecteditemvaluefromaspradiobuttonlistVBnet.htm
答
您还可以使用Request.Form("GroupNameGoesHere")
来获取值该组中当前选定的单选按钮(如果不存在则为空字符串)。
答
使它成为一个单选按钮列表来代替。然后你可以简单地检查List的“SelectedItem”属性。
查看http://www.startvbdotnet.com/aspsite/controls/rblist.aspx的例子。
答
如果你使用上面提到的单选按钮列表,你可以做这样的事情。测试是否选择了某些东西。
<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;