Click here to Skip to main content
11,806,339 members (66,765 online)
Click here to Skip to main content

How to group RadioButtons

, 11 Aug 2004 CPOL 647.4K 11.8K 247
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">
                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" />
        <asp:BoundColumn DataField="Country" HeaderText="Country" 
                                  HeaderStyle-Font-Bold="True" />
        <asp:BoundColumn DataField="Capital" HeaderText="Capital" 
                                  HeaderStyle-Font-Bold="True" />

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" 
        <td> </td>
        <td style="font-weight:bold;">Country</td>
        <td style="font-weight:bold;">Capital</td>
        <td><input id="countriesGrid__ctl2_selectRadioButton" 
             type="radio" name="countriesGrid:_ctl2:country" 
             value="selectRadioButton" /></td>
        <td><input id="countriesGrid__ctl3_selectRadioButton" 
             type="radio" name="countriesGrid:_ctl3:country" 
             value="selectRadioButton" /></td>
    <!-- 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" 
                <vs:GroupRadioButton id="selectRadioButton" 
                runat="server" GroupName="country" />
        <asp:BoundColumn DataField="Country" HeaderText="Country" 
                                  HeaderStyle-Font-Bold="True" />
        <asp:BoundColumn DataField="Capital" HeaderText="Capital" 
                                  HeaderStyle-Font-Bold="True" />

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 = 

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


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


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


About the Author

Vladimir Smirnov
Web Developer
Russian Federation Russian Federation
No Biography provided

You may also be interested in...

Comments and Discussions

GeneralThank you! Pin
GoodQueenJen21-Aug-15 6:28
memberGoodQueenJen21-Aug-15 6:28 
QuestionWow! Pin
No0oshin14-Mar-15 23:42
memberNo0oshin14-Mar-15 23:42 
QuestionAwesome Pin
Member 1017358019-Aug-13 2:40
memberMember 1017358019-Aug-13 2:40 
BugText Label Pin
Fabio Solariwebster25-Jan-13 13:55
memberFabio Solariwebster25-Jan-13 13:55 
QuestionPlz help me Pin
soft.rajasekaran27-Dec-12 17:37
membersoft.rajasekaran27-Dec-12 17:37 
QuestionCSS class not present Pin
karlitr0s11-May-12 1:10
memberkarlitr0s11-May-12 1:10 
Questionthe simplest code ..which serves the purpose Pin
Bilal Mustafa Fazlani9-May-12 21:21
memberBilal Mustafa Fazlani9-May-12 21:21 
QuestionPossible bug? Pin
Gavin Roberts26-Nov-11 11:02
memberGavin Roberts26-Nov-11 11:02 
GeneralThanks! Pin
M.AsimSiddiqui15-Jun-11 4:23
memberM.AsimSiddiqui15-Jun-11 4:23 
GeneralBetter implementation Pin
Martin Zarate27-Apr-11 7:49
memberMartin Zarate27-Apr-11 7:49 
GeneralRe: Better implementation Pin
Chris Clark23-May-11 4:31
memberChris Clark23-May-11 4:31 
GeneralRe: Better implementation Pin
TrendyTim29-Nov-11 21:01
memberTrendyTim29-Nov-11 21:01 
GeneralBetter implementation (C# Version) Pin
flemgrem23-Jan-12 5:02
memberflemgrem23-Jan-12 5:02 
GeneralAwesome ! Pin
Z_KiNGPiN23-Apr-11 21:44
memberZ_KiNGPiN23-Apr-11 21:44 
GeneralMy vote of 5 Pin
ccaspers4-Feb-11 10:12
memberccaspers4-Feb-11 10:12 
GeneralMy vote of 5 Pin
Emeka Awagu11-Nov-10 22:55
memberEmeka Awagu11-Nov-10 22:55 
GeneralFantastic Pin
Member 46201357-Oct-10 5:34
memberMember 46201357-Oct-10 5:34 
GeneralMy vote of 5 Pin
MiroslavBraikov25-Sep-10 22:50
memberMiroslavBraikov25-Sep-10 22:50 
GeneralMy vote of 3 Pin
sarodgl11-Aug-10 5:46
membersarodgl11-Aug-10 5:46 
GeneralMy vote of 5 Pin
Andrew Lansdowne3-Aug-10 22:56
memberAndrew Lansdowne3-Aug-10 22:56 
GeneralMy vote of 3 Pin
ramanarayananAsp29-Jul-10 6:44
memberramanarayananAsp29-Jul-10 6:44 
GeneralYou are IT! Pin
Stevishere27-Apr-10 10:59
memberStevishere27-Apr-10 10:59 
QuestionHow to add Text Property? Pin
DragothiC4-Mar-10 6:12
memberDragothiC4-Mar-10 6:12 
AnswerRe: How to add Text Property? Pin
Chris Clark23-May-11 4:30
memberChris Clark23-May-11 4:30 
GeneralRe: How to add Text Property? Pin
Tellalca8-Sep-11 2:53
memberTellalca8-Sep-11 2:53 
Generalchecked=false all the time Pin
ghassan1008-Oct-09 21:59
memberghassan1008-Oct-09 21:59 
GeneralRe: checked=false all the time Pin
lovingit6-Nov-09 10:54
memberlovingit6-Nov-09 10:54 
GeneralRe: checked=false all the time Pin
Member 46201357-Oct-10 4:55
memberMember 46201357-Oct-10 4:55 
Generalcant find control in groupradiobutton (VB.Net Code) Pin
sarmatvs6-Aug-09 15:07
membersarmatvs6-Aug-09 15:07 
GeneralThanks Pin
halil ibo10-Jul-09 0:04
memberhalil ibo10-Jul-09 0:04 
GeneralThanks! Pin
eriknsdca29-Mar-09 15:57
membereriknsdca29-Mar-09 15:57 
GeneralThanks... I hope MS fixes this in their next release. Good work! Pin
Dire Entity20-Mar-09 14:53
memberDire Entity20-Mar-09 14:53 
GeneralThanks a million for your answer Pin
aungmyo6-Mar-09 3:10
memberaungmyo6-Mar-09 3:10 
GeneralThank you! Pin
John Riston3-Feb-09 5:27
memberJohn Riston3-Feb-09 5:27 
Generalcool! but one suggestion..... Pin
Aravind Rajagopal K5-Dec-08 6:56
memberAravind Rajagopal K5-Dec-08 6:56 
GeneralRe: cool! but one suggestion..... Pin
M.AsimSiddiqui15-Jun-11 4:22
memberM.AsimSiddiqui15-Jun-11 4:22 
Generalthanks very much Pin
George Manjooran5-Nov-08 22:37
memberGeorge Manjooran5-Nov-08 22:37 
Questionhow to give different rows different groupnames? Pin
Thomas19118-Oct-08 23:49
memberThomas19118-Oct-08 23:49 
GeneralChecked=True Pin
VivekVashisht3-Oct-08 19:39
memberVivekVashisht3-Oct-08 19:39 
QuestionHow to group RadioButtons Pin
jemreal30-Sep-08 15:55
memberjemreal30-Sep-08 15:55 
Generalgreat Pin
Ra...aj13-Sep-08 22:59
memberRa...aj13-Sep-08 22:59 
QuestionSystem.Security.SecurityException: That assembly does not allow partially trusted callers. Pin
Member 377988315-Jul-08 23:57
memberMember 377988315-Jul-08 23:57 
QuestionGroupRadioButton.Text & GroupRadioButton.ForeColor Doesnt work !?! Pin
KamiDalton12-Jun-08 3:07
memberKamiDalton12-Jun-08 3:07 
QuestionCan't get which radiobutton is selected.....always gets checked = false Pin
amit_chudasama20-May-08 3:16
memberamit_chudasama20-May-08 3:16 
RantThanks! Pin
agira11-May-08 21:44
memberagira11-May-08 21:44 
GeneralExcellent - Thank you Pin
Geek Queen15-Apr-08 11:58
memberGeek Queen15-Apr-08 11:58 
GeneralRe: Excellent - Thank you Pin
erax dan21-Jul-08 6:16
membererax dan21-Jul-08 6:16 
Generalproblem is related to radio button list Pin
krishnaveer3-Apr-08 4:21
memberkrishnaveer3-Apr-08 4:21 
GeneralCool. thanks a lot Pin
Member 98160612-Mar-08 22:04
memberMember 98160612-Mar-08 22:04 
GeneralThank you Pin
Glebowski11-Mar-08 1:58
memberGlebowski11-Mar-08 1:58 

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
Web02 | 2.8.151002.1 | Last Updated 12 Aug 2004
Article Copyright 2004 by Vladimir Smirnov
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid