Click here to Skip to main content
15,867,453 members
Articles / Web Development / ASP.NET

Grouped Radio Buttons in Gridview

Rate me:
Please Sign up or sign in to vote.
4.69/5 (8 votes)
28 Sep 2010CPOL2 min read 116.3K   2.2K   17   15
Radio buttons in Gridview without JavaScript

Introduction

This is my first article published on The Code Project web site. In this article, I will show you how you can use grouped RadioButtons inside a GridView control.

Main Problem About Radio Buttons in Gridview

The big problem is that we can’t put all the radio buttons into one group in the gridview, although we have set the same group name for them.

The RadioButton's GroupName property is what is used to group a series of radio buttons. All RadioButton controls with the same GroupName value are considered grouped; only one radio button can be selected from a group at a time. The GroupName property specifies the value for the rendered radio button's name attribute. The browser examines the radio buttons name attributes to determine the radio button groupings.

Every row in the gridview has a different ID. So the radiobutton’s GroupName is useless in the gridview.

ASP.NET
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
                    DataKeyNames="EmployeeID" DataSourceID="SqlDataSource1" 
			Font-Names="Verdana" 
                    Font-Size="14px" Width="289px">
                    <Columns>
                        <asp:BoundField DataField="LastName" HeaderText="LastName" 
                            SortExpression="LastName" />
                        <asp:BoundField DataField="FirstName" HeaderText="FirstName" 
                            SortExpression="FirstName" />
                        <asp:TemplateField HeaderText="Useless Group">
                            <ItemTemplate>
                                    <asp:RadioButton ID="MyRadioButton" runat="server" 
                                        GroupName="UselessGroup"  />
                            </ItemTemplate>
                        </asp:TemplateField>

multi-choose.png

If we view source from the browser and check the radio button markup, we will get the following code:

view.png

The result is that we can only select multiple radio buttons, when we want to make a single selection, which is like what we do with checkboxes.

This article will show you how to solve this problem without any JavaScript programming.

Using CheckedChanged event to simulate a group for Radio button in Gridview.

There is an event named checkedchanged in radiobutton control. When this event is triggered, we just deselect all radio buttons in gridview, and then re-select the required radio button. The radio button reselected is the one which triggered the checkedchanged event in the first instance.

ASP.NET
<asp:TemplateField HeaderText="Fake group">
        <ItemTemplate>
            <asp:RadioButton ID="MyRadioButton1" runat="server" 
                     GroupName="FakeGroup"  AutoPostBack="True" 
			OnCheckedChanged="MyRadioButton1_CheckedChanged" />
        </ItemTemplate>
</asp:TemplateField>
VB.NET
Protected Sub MyRadioButton1_CheckedChanged_
	(ByVal sender As Object, ByVal e As System.EventArgs)
        deselect_RB_in_gridview()
        'deselect radiobutton1
        'RadioButton1.Checked = False
        'check the radiobutton which is checked
        Dim SenderRB As RadioButton = sender
        SenderRB.Checked = True
        '--------------------------------------
        'Reflect the event
        '---------------------------------------
        'fire_visible_window()
    End Sub
VB.NET
Sub deselect_RB_in_gridview()
    Dim gvr As GridViewRow
    Dim i As Int32
    'deselect all radiobutton in gridview
    For Each gvr In GridView1.Rows
        Dim rb As RadioButton
        rb = CType(GridView1.Rows(i).FindControl("MyRadioButton1"), RadioButton)
        rb.Checked = False
        i += 1
    Next
End Sub

The function of deselect_RB_in_gridview() will clear all the radio button checked flag.

The two codes below will find the radio button which triggered the CheckedChanged event, and then re-select it.

VB.NET
Dim SenderRB As RadioButton = sender

SenderRB.checked = True

In my source code, I use Northwind database and give add an extra function to the radio gridview. I set a radio button outside the gridview. If you choose the radio button in the gridview, the web page will popup an always visible panel and show your selection in it. If you select the outside radio button, all the radio buttons in the gridview will be cleared and that always visible panel will disappear as well.

visible.png

I hope you like it. Happy coding!

History

  • 28th September, 2010: Initial post

License

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


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

Comments and Discussions

 
QuestionHow to Get Radio Button Value in PHP Without Submit Pin
azeem ali21-Jun-20 23:25
azeem ali21-Jun-20 23:25 
PraiseExactly what was needed Pin
Eric666111-Apr-16 8:28
Eric666111-Apr-16 8:28 
QuestionVery good Article Pin
ratanram3-Nov-14 21:09
ratanram3-Nov-14 21:09 
AnswerRe: Very good Article Pin
Tim_w8-Nov-14 10:42
Tim_w8-Nov-14 10:42 
QuestionExcellent Pin
katlegoEmmnanuelNkosi22-Oct-13 3:24
katlegoEmmnanuelNkosi22-Oct-13 3:24 
GeneralExcellent! Pin
dedamu6-Jun-13 16:07
professionaldedamu6-Jun-13 16:07 
GeneralRe: Excellent! Pin
Tim_w9-Jun-13 11:17
Tim_w9-Jun-13 11:17 
GeneralAnother option Pin
Richard Deeming5-Oct-10 8:15
mveRichard Deeming5-Oct-10 8:15 
If you're running in full trust, and your not afraid of a little reflection, you can create a custom RadioButton which doesn't require AutoPostBack:

C#
using System;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Reflection;
using System.Security.Permissions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

[AspNetHostingPermission(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
[AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
public class SimpleRadioButton : RadioButton
{
    private static readonly FieldInfo UniqueGroupNameField = FindUniqueGroupNameField();
    private string _uniqueGroupName;

    private static FieldInfo FindUniqueGroupNameField()
    {
        return typeof(RadioButton).GetField("_uniqueGroupName", 
            BindingFlags.NonPublic | BindingFlags.Instance);
    }

    protected virtual string CreateUniqueGroupName()
    {
        string result = this.GroupName;
        if (string.IsNullOrEmpty(result))
        {
            result = this.ID;
        }
        if (string.IsNullOrEmpty(result))
        {
            result = this.UniqueID;
        }
        else
        {
            Control container = this.NamingContainer;
            if (null != container)
            {
                if (container is IDataItemContainer)
                {
                    container = container.NamingContainer ?? container;
                }

                result = container.UniqueID + base.IdSeparator + result;
            }
            else
            {
                string uniqueID = this.UniqueID;
                if (!string.IsNullOrEmpty(uniqueID))
                {
                    int index = uniqueID.LastIndexOf(base.IdSeparator);
                    if (-1 != index)
                    {
                        result = uniqueID.Substring(0, 1 + index) + result;
                    }
                }
            }
        }

        return result;
    }

    private void EnsureUniqueGroupName()
    {
        if (null == _uniqueGroupName)
        {
            string value = this.CreateUniqueGroupName();
            if (null != UniqueGroupNameField) UniqueGroupNameField.SetValue(this, value);
            _uniqueGroupName = value;

            // Make sure we have a value attribute:
            value = base.Attributes["value"];
            if (string.IsNullOrEmpty(value))
            {
                base.Attributes["value"] = this.UniqueID;
            }
        }
    }

    protected override bool LoadPostData(string postDataKey, NameValueCollection postCollection)
    {
        this.EnsureUniqueGroupName();
        return base.LoadPostData(postDataKey, postCollection);
    }

    protected override void Render(HtmlTextWriter writer)
    {
        this.EnsureUniqueGroupName();
        base.Render(writer);
    }
}


With this control, if the parent container implements IDataItemContainer, it will try to use the ID of the container's container to build the group name. Since all of the built-in list controls use containers which implement IDataItemContainer, this control will work within them as expected.

NB: By default, if you set an explicit ID on the RadioButton without setting the value attribute, the value will be set to the ID, which won't work. To avoid this, if the value attribute isn't set, I've explicitly set it to the UniqueID of the control.



"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer


GeneralRe: Another option Pin
Tim_w5-Oct-10 10:42
Tim_w5-Oct-10 10:42 
GeneralMy vote of 5 Pin
Rahul Khadikar28-Sep-10 18:30
Rahul Khadikar28-Sep-10 18:30 
GeneralRe: My vote of 5 Pin
Tim_w29-Sep-10 16:47
Tim_w29-Sep-10 16:47 
GeneralSource code readability Pin
Praveen Nair (NinethSense)28-Sep-10 0:54
Praveen Nair (NinethSense)28-Sep-10 0:54 
GeneralRe: Source code readability Pin
Tim_w28-Sep-10 1:37
Tim_w28-Sep-10 1:37 
GeneralRe: Source code readability Pin
dishantmudgal26-Sep-12 17:33
dishantmudgal26-Sep-12 17:33 

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.