Click here to Skip to main content
15,878,945 members
Articles / Web Development / ASP.NET
Article

How to group RadioButtons

Rate me:
Please Sign up or sign in to vote.
4.88/5 (132 votes)
11 Aug 2004CPOL2 min read 858.7K   12.8K   246   154
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:

HTML
<!-- 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:

HTML
<!-- 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:

ASP.NET
<%@ 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:

C#
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)


Written By
Web Developer
Russian Federation Russian Federation
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionSystem.Security.SecurityException: That assembly does not allow partially trusted callers. Pin
Member 377988315-Jul-08 23:57
Member 377988315-Jul-08 23:57 
QuestionGroupRadioButton.Text & GroupRadioButton.ForeColor Doesnt work !?! Pin
Kamran Hazari12-Jun-08 3:07
Kamran Hazari12-Jun-08 3:07 
QuestionCan't get which radiobutton is selected.....always gets checked = false Pin
Amit_Chudasama20-May-08 3:16
Amit_Chudasama20-May-08 3:16 
RantThanks! Pin
agira11-May-08 21:44
agira11-May-08 21:44 
GeneralExcellent - Thank you Pin
Geek Queen15-Apr-08 11:58
Geek Queen15-Apr-08 11:58 
GeneralRe: Excellent - Thank you Pin
erax dan21-Jul-08 6:16
erax dan21-Jul-08 6:16 
Generalproblem is related to radio button list Pin
krishnaveer3-Apr-08 4:21
krishnaveer3-Apr-08 4:21 
GeneralCool. thanks a lot Pin
Member 98160612-Mar-08 22:04
Member 98160612-Mar-08 22:04 
Very nice solution

f0rza: http://bulenok.com
GeneralThank you Pin
Glebowski11-Mar-08 1:58
Glebowski11-Mar-08 1:58 
GeneralNice Pin
anzatechnologies13-Mar-08 21:20
anzatechnologies13-Mar-08 21:20 
GeneralGreat Thanks Pin
sstrega20-Feb-08 15:18
sstrega20-Feb-08 15:18 
QuestionGetting error .. Pin
umesh0929-Jan-08 23:20
umesh0929-Jan-08 23:20 
GeneralRe: Getting error .. Pin
umesh0929-Jan-08 23:39
umesh0929-Jan-08 23:39 
GeneralRe: Getting error .. Pin
Member 377988315-Jul-08 23:53
Member 377988315-Jul-08 23:53 
GeneralRe: Getting error .. Pin
sherazl14-May-09 2:21
sherazl14-May-09 2:21 
GeneralBrilliant idea - saved much time Pin
saille21-Nov-07 14:51
saille21-Nov-07 14:51 
QuestionHow can I add ATTRIBUTES? (help) Pin
alexvw1-Nov-07 5:53
alexvw1-Nov-07 5:53 
AnswerRe: How can I add ATTRIBUTES? (help) Pin
David Hay3-Mar-08 14:24
David Hay3-Mar-08 14:24 
GeneralThanks David Pin
alexvw4-Mar-08 8:09
alexvw4-Mar-08 8:09 
Generalthanks !! Save my time Pin
PragneshMPatel27-Sep-07 3:18
PragneshMPatel27-Sep-07 3:18 
GeneralRe: thanks !! Save my time Pin
but khoeun8-Dec-08 0:38
but khoeun8-Dec-08 0:38 
QuestionLicense for use? Pin
MediaNick31-Aug-07 4:01
MediaNick31-Aug-07 4:01 
GeneralText property did not render properly Pin
Gbillou_7-Aug-07 22:00
Gbillou_7-Aug-07 22:00 
Generalbest! even 3 years after publishing this.... Pin
shlomiw17-Jun-07 7:16
shlomiw17-Jun-07 7:16 
QuestionHow to make RadioButton a Select command Pin
jonathonS29-May-07 10:48
jonathonS29-May-07 10:48 

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

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