How do i access a radio button control that i dynamically added on my code behind page to find out if it's checked or not?

Posted on 2004-11-05
Last Modified: 2008-01-09
I have successfully created the code to generate a number of radiobuttons dynamically in my app.  The problem i'm having now is detecting which radiobuttons that have been checked by the user when they click the "Next" button.  

Any ideas?

Question by:FPIT
    LVL 32

    Expert Comment

    Like this ?

    <script language="JavaScript" type="text/javascript">
    function checkedRadio() {
       var isChecked = false;
       var myForm = document.myform;
       for(var i=0; i<myForm.myTopics.length; i++) {
           if(myForm.myTopics[i].checked) {
               isChecked = true;
          alert("Nothing checked!");
    <form name="myform" method="post" action="" >
    <input type="radio" name="myTopics" value="php"> php
    <input type="radio" name="myTopics" value="jsp"> jsp
    <input type="radio" name="myTopics" value="javascript"> javascript
    <input type="radio" name="myTopics" value="mysql"> mysql
    <input type="button" value="Next" onclick="checkedRadio()"/>

    If server side, whatever you "checked" only be passed in the next page. For example,

    in PHP:
    $checkedRadio = isset($_POST["myTopics"]) ? $_POST["myTopics"] : "";

    in JSP:
    String checkedRadio = (request.getParameter("myTopics") != null) ? request.getParameter("myTopics") : "";

    LVL 3

    Expert Comment

    by you mentioning the codebehind, im assuming you are talking about ASP .NET and code behind in VB .NET. for that purpose on you radio button,
    set the AutoPostBack property to true

    rdoTest.AutoPostback = true

    and to recieve events,


    AddHandler rdoTest.CheckChanged, AddressOf theFunctionThtShouldRunWhenTheEventOccurs
    here u need to write this

    function theFunctionThtShouldRunWhenTheEventOccurs(sender as Object, e as EventArgs)
    end function

    which takes care of what happens when the event occurs.

    hope this helps

    Author Comment

    Yes sorry about that...i'm using ASP.NET (VB.NET for the code-behind pages).  I'm generating a set of Radio Buttons on the fly from the code-behind page because the number of radio buttons being used (if any) solely depends on who's using the system.  So i need to create these buttons on the fly instead of hard coding in a set of buttons like "ldbkutty" suggested above.  I have no problem creating the buttons, but i can't seem to figure out for the life of me how to capture which buttons where checked.  I've tried the autopostback = true property, which works fine, but i don't know how to add the event handler to trigger my function when a button is clicked.  Ordinarily you see the CheckedChanged event property in the intellisense, but i am not getting any events whatsoever to choose from in the code when i'm creating the button.  So how do i add the event handler to each radio button to call the function that you've written above?   I'll give you some of my code to look at, hopefully that will help out and not confuse anyone.....

    So basically i find out how many radio buttons this user will be using by querying the's the SqlDataReader loop that iterates through each record producing a radio button group (3 buttons per group which represents Good, Needs Improvement and Not Applicable).  Each of the buttons are added to a TableCell (td) which is then added to a TableRow (tr) and finally added to an ASP:Table.  

    Here's the code:

    Do While topics.Read()
                        Dim tr2 As TableRow
                        Dim td2, td3, td4, td5 As TableCell
                        Dim lbl_topic As Label
                        Dim tbh_topic_id As TextBox
                        Dim rb1, rb2, rb3 As RadioButton
                        Dim rb1_name, rb2_name, rb3_name, rb_group_name As String

                        tr2 = New TableRow()
                        td2 = New TableCell()
                        td3 = New TableCell()
                        td4 = New TableCell()
                        td5 = New TableCell()
                        rb1 = New RadioButton()
                        rb2 = New RadioButton()
                        rb3 = New RadioButton()                    
                        rb1_name = "rb_good_" & topic_id
                        rb2_name = "rb_ni_" & topic_id
                        rb3_name = "rb_na_" & topic_id
                        rb_group_name = "rb_group_" & y

                        'Creating radionbutton 1
                         rb1.ID = rb1_name
                         rb1.GroupName = rb_group_name
                         rb1.AutoPostBack = True
                        'RIGHT HERE I SHOULD BE ABLE TO ADD THE EVENT HANDLER LIKE: rb1.CheckChanged("rb_CheckChanged") or something to that effect...but can't!

                         'Creating radio button 2
                         rb2.ID = rb2_name
                         rb2.GroupName = rb_group_name

                        'Creating radio button 3
                         rb3.ID = rb3_name
                         rb3.GroupName = rb_group_name

                        'Assigning radiobuttons 1, 2 and 3 to a TableCell and formatting the tablecell's width etc...
                         td3.Width = px.Percentage(10%)
                         td3.HorizontalAlign = HorizontalAlign.Center
                         td4.Width = px.Percentage(25%)
                         td4.HorizontalAlign = HorizontalAlign.Center
                         td5.Width = px.Percentage(15%)
                         td5.HorizontalAlign = HorizontalAlign.Center

                         y += 1

    That's how i created the radio i need to know how to find out which ones where selected when the user clicks the Next button....i'd prefer not to autopostback on each click if possible.  Ideally i want to check each button once when the "Next" button is clicked.  

    Any help would be greatly appreciated...thanks

    Author Comment

    I should also tell you that the ASP:Table that holds the TableRow and TableCell which holds the Radio Buttons that i've created are added to a PlaceHolder that i have in the HTML page for example:

    <asp:PlaceHolder id="ph_form" Runat="server"></asp:PlaceHolder>

    The line above sits in my Form.aspx html page and i add the table with my radio buttons in it to this place holder.  So i've tried accessing the radio buttons by using the FindControl function on the ph_form place holder field too, but no luck.  For example, in my code-behind page i have an onClick function that is called when the user clicks the "Next" button that i have's the code from that page that i've tried with no luck as well....perhaps that help too...

    Sub saveForm(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs)
            Dim rb1, rb2, rb3 As RadioButton
            Dim gradeType As String
            Dim topics As SqlDataReader
            Dim property_id, section_id, curPage As Integer
            Dim retVal As Boolean

            'rb1 = New RadioButton()
            'rb2 = New RadioButton()
            'rb3 = New RadioButton()

            property_id = Session.Item("property_id")
            curPage = currentPage()
            section_id = mod_info.getPropertyForm(property_id, curPage)
            topics = mod_info.getForm(property_id, section_id)
            gradeType = Session.Item("gradeType")

            Do While topics.Read()
                    rb1 = ph_form.FindControl("rb_good_" & topics(0))
                    Response.Write("rb_good_" & topics(0))
                    rb1 = CType(FindControl("rb_good_" & topics(0)).Controls(0), RadioButton)
                    rb2 = ph_form.FindControl("rb_ni_" & topics(0))
                    rb3 = ph_form.FindControl("rb_na_" & topics(0))
                   If rb1.Checked = True Then
                        Response.Write("It's checked")
                        Response.Write("It's NOT checked")
                   End If
    End Sub

    I've tried several different ways as you can see above, plus others and i can't get it to work.  The above code may produce an error, i'm not sure i had most of it commented out as i've been trying different scenarios.   I just figured i could create a new instance of a radio button rb1 (above) and use the FindControl function to pass the values from the already created radio button to the new instance and see if it's checked that way.....Hopefully this isn't confusing you.

    Any ideas?  
    Thanks again....
    LVL 3

    Accepted Solution


    If you want to check the status of each radiobutton when clicked then you do not need events or autopsot back. You can use the request.form("NameOfYourRadioButton"), this would return the name of the radio button if it is checked and nothing if it is not. Put this code in ur button click event handler function and let me know if it helps

    LVL 3

    Expert Comment

    And by Name of the Radio button i mean the id of it, not "name" litereally. Sorry if that caused any confusion.

    LVL 3

    Expert Comment

    And for the other part: event handlers are not added the way mentioned

                        rb1.AutoPostBack = True
                        'RIGHT HERE I SHOULD BE ABLE TO ADD THE EVENT HANDLER LIKE: rb1.CheckChanged("rb_CheckChanged") or something to that effect...but can't!
    the syntax is

    AddHandler rb1.CheckChanged, AddressOf rb_checkchanged           'This is the exact syntax


    Author Comment

    Awesome thanks...i'll try it out!

    Author Comment

    Hey Vippex,

    Thanks alot, i used the request.form("name of radio button group") and that worked.  Nothing was returned when i used the actual id of each radio button as you suggested (or i think you suggested).  So i tried using the radio button group name and it worked perfectly.  I can't believe i didn't think to try that!  I did try request.querystring and request.servervariables to see what that returned but had no luck becuase i don't think i realized that only the name of the button would be returned if it's selected.  Anyhow, it works now thanks to you!

    'Creating radionbutton 1
          rb1.ID = rb1_name
          rb1.GroupName = rb_group_name

    I used the value of rb_group_name to get what i was looking for not the value of rb1_name.  Also the AddHandler syntax worked perfectly too....thanks for that as well because i'm sure i'll need that somewhere along the way too!  

    Thanks again!

    Featured Post

    How to run any project with ease

    Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
    - Combine task lists, docs, spreadsheets, and chat in one
    - View and edit from mobile/offline
    - Cut down on emails

    Join & Write a Comment

    Suggested Solutions

    Title # Comments Views Activity
    twoTwo  challenge 35 73
    method argument as final 1 54
    add text to end of existing text in file 16 54
    mergeTwo  challenge 13 55
    This article will show, step by step, how to integrate R code into a R Sweave document
    Entering a date in Microsoft Access can be tricky. A typo can cause month and day to be shuffled, entering the day only causes an error, as does entering, say, day 31 in June. This article shows how an inputmask supported by code can help the user a…
    An introduction to basic programming syntax in Java by creating a simple program. Viewers can follow the tutorial as they create their first class in Java. Definitions and explanations about each element are given to help prepare viewers for future …
    Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

    755 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    20 Experts available now in Live!

    Get 1:1 Help Now