Click here to Skip to main content
Licence CPOL
First Posted 11 Aug 2004
Views 483,427
Downloads 7,877
Bookmarked 238 times

How to group RadioButtons

By Vladimir Smirnov | 11 Aug 2004
This article describes how to group radio-buttons when using them in DataGrid, DataList, Repeater etc.
2 votes, 1.6%
1
1 vote, 0.8%
2
5 votes, 4.0%
3
13 votes, 10.5%
4
103 votes, 83.1%
5
4.88/5 - 124 votes
8 removed
μ 4.75, σa 1.27 [?]

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)

About the Author

Vladimir Smirnov

Web Developer

Russian Federation Russian Federation

Member


Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionPossible bug? PinmemberGavin Roberts12:02 26 Nov '11  
GeneralThanks! PinmemberM.AsimSiddiqui5:23 15 Jun '11  
GeneralBetter implementation PinmemberMartin Zarate8:49 27 Apr '11  
GeneralRe: Better implementation PinmemberChris Clark5:31 23 May '11  
GeneralRe: Better implementation PinmemberTrendyTim22:01 29 Nov '11  
GeneralBetter implementation (C# Version) [modified] Pinmemberflemgrem6:02 23 Jan '12  
GeneralAwesome ! PinmemberZ_KiNGPiN22:44 23 Apr '11  
GeneralMy vote of 5 Pinmemberccaspers11:12 4 Feb '11  
GeneralMy vote of 5 PinmemberEmeka Awagu23:55 11 Nov '10  
GeneralFantastic PinmemberMember 46201356:34 7 Oct '10  
GeneralMy vote of 5 PinmemberMiroslavBraikov23:50 25 Sep '10  
GeneralMy vote of 3 Pinmembersarodgl6:46 11 Aug '10  
GeneralMy vote of 5 PinmemberAndrew Lansdowne23:56 3 Aug '10  
GeneralMy vote of 3 PinmemberramanarayananAsp7:44 29 Jul '10  
GeneralYou are IT! PinmemberStevishere11:59 27 Apr '10  
QuestionHow to add Text Property? PinmemberDragothiC7:12 4 Mar '10  
AnswerRe: How to add Text Property? PinmemberChris Clark5:30 23 May '11  
GeneralRe: How to add Text Property? PinmemberTellalca3:53 8 Sep '11  
Generalchecked=false all the time Pinmemberghassan10022:59 8 Oct '09  
GeneralRe: checked=false all the time Pinmemberlovingit11:54 6 Nov '09  
GeneralRe: checked=false all the time PinmemberMember 46201355:55 7 Oct '10  
Generalcant find control in groupradiobutton (VB.Net Code) Pinmembersarmatvs16:07 6 Aug '09  
GeneralThanks Pinmemberhalil ibo1:04 10 Jul '09  
GeneralThanks! Pinmembereriknsdca16:57 29 Mar '09  
GeneralThanks... I hope MS fixes this in their next release. Good work! PinmemberDire Entity15:53 20 Mar '09  

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.

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