Click here to Skip to main content
Click here to Skip to main content

How to group RadioButtons

, 11 Aug 2004 CPOL
Rate this:
Please Sign up or sign in to vote.
This article describes how to group radio-buttons when using them in DataGrid, DataList, Repeater etc.

Introduction to the problem

'Where is the problem? Haven't you heard about GroupName property?' - you can ask me. Of course, you are right! But...

Let's take an ordinary DataGrid, add a TemplateColumn to its Columns collection, and place a RadioButton control within this column (it can be useful when you would like to provide the user with selection from the DataGrid items). See the code below:

<!-- Countries for selection -->
<asp:DataGrid id="countriesGrid" runat="server" 
         DataKeyField="ID" AutoGenerateColumns="False">
    <Columns>
        <asp:TemplateColumn>
            <ItemTemplate>
                <!-- 
                Draw attention at this control. 
                We would like to use radio-buttons to
                select single country from the list.
                -->
                <asp:RadioButton id="selectRadioButton" 
                    runat="server" GroupName="country" />
            </ItemTemplate>
        </asp:TemplateColumn>
        <asp:BoundColumn DataField="Country" HeaderText="Country" 
                                  HeaderStyle-Font-Bold="True" />
        <asp:BoundColumn DataField="Capital" HeaderText="Capital" 
                                  HeaderStyle-Font-Bold="True" />
    </Columns>
</asp:DataGrid>

Now, bind to the DataGrid some data and run your ASP.NET application. Try to click at the radio buttons in the Countries list. You can select one country!... and another one... and another... Hmm-m! Didn't we really want to get this effect?

Where is a mistake? We have specified GroupName for the RadioButtons to treat them as from the single group, haven't we? Look at the piece of HTML code that has been generated from our web form. You will see something like this:

<!-- Countries for selection -->
<table cellspacing="0" rules="all" border="1" id="countriesGrid" 
                              style="border-collapse:collapse;">
    <tr>
        <td> </td>
        <td style="font-weight:bold;">Country</td>
        <td style="font-weight:bold;">Capital</td>
    </tr>
    <tr>
        <td><input id="countriesGrid__ctl2_selectRadioButton" 
             type="radio" name="countriesGrid:_ctl2:country" 
             value="selectRadioButton" /></td>
        <td>USA</td>
        <td>Washington</td>
    </tr>
    <tr>
        <td><input id="countriesGrid__ctl3_selectRadioButton" 
             type="radio" name="countriesGrid:_ctl3:country" 
             value="selectRadioButton" /></td>
        <td>Canada</td>
        <td>Ottawa</td>
    </tr>
    <!-- etc. -->

The 'name' attributes of the radio-buttons are different. Why? Here is the answer.

When rendering RadioButton control, ASP.NET uses concatenation of GroupName and UniqueID for the value of 'name' attribute. So, this attribute depends on the UniqueID of the control which depends on the owner's UniqueID etc. It is the standard solution of ASP.NET to avoid naming collisions. As the value of the 'name' attribute of the <input type="radio" /> is used for identification of postback data of the radio-button group when the from is submitting, ASP.NET developers decided to isolate radio-button groups within the bounds of the single owner control (i.e., any two radio-buttons from the same group can not have different direct owners), otherwise it can occur that you will use two third party controls that both contain radio-button groups with the same GroupName - in this case, all radio-buttons will be treated as from the single group and that will bring undesirable behavior.

Now you have understood the cause of error, but how to implement the feature we want? In the next section, I'll provide you the solution.

Solution of the problem

To solve the problem I have stated above, I've created a new GroupRadioButton web control derived from the RadioButton.

In this control, I have changed the rendering method so that 'name' attribute of the resulting HTML radio-button now depends on the GroupName only.

Another one modification is postback data handling (IPostBackDataHandler interface has been overridden).

Other functionality of the GroupRadioButton is equivalent to RadioButton.

See the source code of the GroupRadioButton for details.

Using the code

Now, let's modify the initial form. Use the following script for the Countries list:

<%@ Register TagPrefix="vs" Namespace="Vladsm.Web.UI.WebControls" 
                                          Assembly="GroupRadioButton" %>
...
<!-- Countries for selection -->
<asp:DataGrid id="countriesGrid" runat="server" DataKeyField="ID" 
                                     AutoGenerateColumns="False">
    <Columns>
        <asp:TemplateColumn>
            <ItemTemplate>
                <vs:GroupRadioButton id="selectRadioButton" 
                runat="server" GroupName="country" />
            </ItemTemplate>
        </asp:TemplateColumn>
        <asp:BoundColumn DataField="Country" HeaderText="Country" 
                                  HeaderStyle-Font-Bold="True" />
        <asp:BoundColumn DataField="Capital" HeaderText="Capital" 
                                  HeaderStyle-Font-Bold="True" />
    </Columns>
</asp:DataGrid>

Add reference to the GroupRadioButton assembly, bind data for the countriesGrid, and execute this form. You will find that all radio-buttons are in the single group (i.e., user can check only one of them).

It remained only to show how to determine which of the countries have been selected:

using Vladsm.Web.UI.WebControls;
...
private void selectButton_Click(object sender, System.EventArgs e)
{
    // for each grid items...
    foreach(DataGridItem dgItem in countriesGrid.Items)
    {
        // get GroupRadioButton object...
        GroupRadioButton selectRadioButton = 
            dgItem.FindControl("selectRadioButton") as GroupRadioButton;

        // if it is checked (current item is selected)...
        if(selectRadioButton != null && selectRadioButton.Checked)
        {
            // sample data that was boud to the countriesGrid
            DataTable dataSource = DataSource.CreateSampleDataSource();

            // get country corresponding to the current item...
            DataRow row = 
              dataSource.Rows.Find(countriesGrid.DataKeys[dgItem.ItemIndex]);

            // ...and show selected country information
            selectedCountryInfo.Text = 
                String.Format("Selected country: {0}, Capital: {1}", 
                row["Country"], row["Capital"]);

            return;
        }
    }

    // there are no selected countries
    selectedCountryInfo.Text = String.Empty;
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Vladimir Smirnov
Web Developer
Russian Federation Russian Federation
No Biography provided

Comments and Discussions

 
QuestionAwesome PinmemberMember 1017358019-Aug-13 3:40 
BugText Label PinmemberFabio Solariwebster25-Jan-13 14:55 
QuestionPlz help me Pinmembersoft.rajasekaran27-Dec-12 18:37 
QuestionCSS class not present Pinmemberkarlitr0s11-May-12 2:10 
Questionthe simplest code ..which serves the purpose PinmemberBilal Mustafa Fazlani9-May-12 22:21 
QuestionPossible bug? PinmemberGavin Roberts26-Nov-11 12:02 
GeneralThanks! PinmemberM.AsimSiddiqui15-Jun-11 5:23 
GeneralBetter implementation PinmemberMartin Zarate27-Apr-11 8:49 
GeneralRe: Better implementation PinmemberChris Clark23-May-11 5:31 
GeneralRe: Better implementation PinmemberTrendyTim29-Nov-11 22:01 
GeneralBetter implementation (C# Version) [modified] Pinmemberflemgrem23-Jan-12 6:02 
GeneralAwesome ! PinmemberZ_KiNGPiN23-Apr-11 22:44 
GeneralMy vote of 5 Pinmemberccaspers4-Feb-11 11:12 
GeneralMy vote of 5 PinmemberEmeka Awagu11-Nov-10 23:55 
GeneralFantastic PinmemberMember 46201357-Oct-10 6:34 
GeneralMy vote of 5 PinmemberMiroslavBraikov25-Sep-10 23:50 
GeneralMy vote of 3 Pinmembersarodgl11-Aug-10 6:46 
GeneralMy vote of 5 PinmemberAndrew Lansdowne3-Aug-10 23:56 
GeneralMy vote of 3 PinmemberramanarayananAsp29-Jul-10 7:44 
GeneralYou are IT! PinmemberStevishere27-Apr-10 11:59 
QuestionHow to add Text Property? PinmemberDragothiC4-Mar-10 7:12 
AnswerRe: How to add Text Property? PinmemberChris Clark23-May-11 5:30 
GeneralRe: How to add Text Property? PinmemberTellalca8-Sep-11 3:53 
Generalchecked=false all the time Pinmemberghassan1008-Oct-09 22:59 
GeneralRe: checked=false all the time Pinmemberlovingit6-Nov-09 11:54 
GeneralRe: checked=false all the time PinmemberMember 46201357-Oct-10 5:55 
Generalcant find control in groupradiobutton (VB.Net Code) Pinmembersarmatvs6-Aug-09 16:07 
GeneralThanks Pinmemberhalil ibo10-Jul-09 1:04 
GeneralThanks! Pinmembereriknsdca29-Mar-09 16:57 
GeneralThanks... I hope MS fixes this in their next release. Good work! PinmemberDire Entity20-Mar-09 15:53 
GeneralThanks a million for your answer Pinmemberaungmyo6-Mar-09 4:10 
GeneralThank you! PinmemberJohn Riston3-Feb-09 6:27 
Generalcool! but one suggestion..... PinmemberAravind Rajagopal K5-Dec-08 7:56 
GeneralRe: cool! but one suggestion..... PinmemberM.AsimSiddiqui15-Jun-11 5:22 
Generalthanks very much PinmemberGeorge Manjooran5-Nov-08 23:37 
Questionhow to give different rows different groupnames? PinmemberThomas19119-Oct-08 0:49 
GeneralChecked=True PinmemberVivekVashisht3-Oct-08 20:39 
QuestionHow to group RadioButtons Pinmemberjemreal30-Sep-08 16:55 
Generalgreat PinmemberRa...aj13-Sep-08 23:59 
QuestionSystem.Security.SecurityException: That assembly does not allow partially trusted callers. PinmemberMember 377988316-Jul-08 0:57 
QuestionGroupRadioButton.Text & GroupRadioButton.ForeColor Doesnt work !?! PinmemberKamiDalton12-Jun-08 4:07 
QuestionCan't get which radiobutton is selected.....always gets checked = false Pinmemberamit_chudasama20-May-08 4:16 
RantThanks! Pinmemberagira11-May-08 22:44 
GeneralExcellent - Thank you PinmemberGeek Queen15-Apr-08 12:58 
GeneralRe: Excellent - Thank you Pinmembererax dan21-Jul-08 7:16 
Generalproblem is related to radio button list Pinmemberkrishnaveer3-Apr-08 5:21 
GeneralCool. thanks a lot PinmemberMember 98160612-Mar-08 23:04 
GeneralThank you PinmemberGlebowski11-Mar-08 2:58 
GeneralNice Pinmemberanzatechnologies13-Mar-08 22:20 
GeneralGreat Thanks Pinmembersstrega20-Feb-08 16:18 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.141216.1 | Last Updated 12 Aug 2004
Article Copyright 2004 by Vladimir Smirnov
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid