views:

159

answers:

5

I have group of radio buttons, each group ranges from 5 - 27 radiobuttons. And if any radio button in a group is checked I store 1 in db else I store 0. Now I'm checking each radiobutton using if loop to see if they are checked and set database value. I'm also trying to use the code below. Is there a good/better approach to check if they are checked or not?

Current code:

'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

Note: I cannot use radio button list. I know this can be achieved easily using this but i want to get solution for radiobutton

+1  A: 

Is it possible for you to use a radiobuttonlist

see: http://www.java2s.com/Code/ASP/Asp-Control/GetselecteditemvaluefromaspradiobuttonlistVBnet.htm

Ivo
A: 

You can also use Request.Form("GroupNameGoesHere") to get the value of the currently selected radio button in that group (or an empty string if none exist).

David L.-Pratte
A: 

Either way, it's up to you.
You'll get the needed performance boost only if you exit the iteration after finding the checked item.

You can modify the iteration as follows:

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
Alex Essilfie
A: 

Make it a RadioButtonList instead. Then you can simply check the "SelectedItem" property of the List.

Look at http://www.startvbdotnet.com/aspsite/controls/rblist.aspx for examples.

Streamcap
A: 

If you use a radiobutton list as mentioned you could do something like this. To test if something was selected.

<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;
madcapnmckay