2010-08-11 178 views
1

我有一组单选按钮,每个组的范围是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 

注:我不能用单选按钮列表。我知道这很容易使用这个来实现,但是我想要得到的单选按钮

回答

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 
     Exit For 
    End If 
Next 
0

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

0

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

<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; 
相关问题