rs.
rs.

Reputation: 27417

How to check if a radiobutton is checked in a group

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

Upvotes: 1

Views: 11150

Answers (5)

madcapnmckay
madcapnmckay

Reputation: 15984

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;

Upvotes: 0

Johan Str&#246;mhielm
Johan Str&#246;mhielm

Reputation: 197

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.

Upvotes: 0

Alex Essilfie
Alex Essilfie

Reputation: 12613

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

Upvotes: 0

David Pratte
David Pratte

Reputation: 1036

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).

Upvotes: 0

Ivo
Ivo

Reputation: 3436

Is it possible for you to use a radiobuttonlist

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

Upvotes: 1

Related Questions