Search code examples
asp.netvb.netradio-button

How to select/ check radio button based on the value from database?


I have radio button like below

 <dx:ASPxRadioButtonList ID="radClaimType" runat="server" RepeatDirection="Horizontal" AutoPostBack="true" ValueType="System.String" Border-BorderStyle="None">
    <Items>
      <dx:ListEditItem Text="Expenses" Value="1" />
      <dx:ListEditItem Text="Travel" Value="2" />
    </Items>
</dx:ASPxRadioButtonList>

How do I select/check the radio button based on the value that I have inserted in database ?

Here is my code behind

Dim dt As New Datatable 
Dim strSelect As String = "SELECT claim_type FROM detail_table WHERE id = '30'"
Dim myconn As New clsConnection

Try
       myconn.OpenConnection()
       myconn.FillDataTable(dt, strSelect)
       myconn.CloseConnection()
    
       If dt.Rows.Count > 0 Then  
         
           If dt.Rows(0).Item("claim_type") = 1 Then
             radClaimType.SelectedIndex = 1
           ElseIf dt.Rows(0).Item("claim_type") = 2 Then
             radClaimType.SelectedIndex = 2
           End If
      
          radClaimType.Enabled = False

       End If
Catch ex As Exception
 MsgBox("Error")
myconn.CloseConnection()
End Try

The result is like this which is incorrect because the claim_type value for id = '30' is 1 which is Expense. I have debug the code and the value for claim_type is indeed 1 but the radio button does not checked/selected to Expense. How do I correct this ?

enter image description here


Solution

  • You should tag what 3rd party control library you are using here.

    Anyway, as a general rule, the asp.net RB-list can be set by "index", starting at 0, or you can set by value.

    So, for your code, then this:

    radClaimType.SelectedValue = dt.Rows(0).Item("claim_type")
    

    You do NOT want to set by index, since the RB list could have ANY values, and

     0 = first one
     1 = 2nd one
     etc. etc. etc.
    

    So, index starts at 0

    but, you want to set the RB by "value", and hence:

    radClaimType.SelectedValue = dt.Rows(0).Item("claim_type")
    

    You can check your documentaton for that control (I don't have it).

    But, you don't need a "if/then" here. You can set the value of the RB, and it should then select/display the value corectly

    so with this:

            <asp:RadioButtonList ID="RadioButtonList1" runat="server"
                RepeatDirection="Horizontal" AutoPostBack="true" >
                <asp:ListItem Value="100">Expenses</asp:ListItem>
                <asp:ListItem Value="200">Travel</asp:ListItem>
            </asp:RadioButtonList>
    

    Then I can set 0 (first) or 1 (second) using "indexing" like this:

    RadioButtonList1.SelectedIndex = 0    ' would select the 100
    RadioButtonList1.SelectedIndex = 1    ' would select the 200
    

    Or, by value

    RadioButtonList1.SelectedValue = 100   ' would select the first one