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

Handling RadioButtons on DataGrid

Rate me:
Please Sign up or sign in to vote.
4.33/5 (8 votes)
6 May 2005 77K   1K   47   7
This article resolves how to manage RadioButtons on the DataGrid.

Introduction

When I had to develop a DataGrid that could handle an option for the user, I found the same problem perfectly described by Vladimir Smirnov in his article "How to Group RadioButtons". However, taking into account the nature of the project, I couldn't use an external DLL. So I decided to handle it by using JavaScript.

Background

The idea is to call a JavaScript script when the user clicks the RadioButton to know which RadioButton was clicked, and thus uncheck the rest of them. To call that JavaScript, we must find the control RadioButton in the ItemDataBound event handler of the DataGrid, add the "onclick" attribute and pass the ClientID of the RadioButton to the JavaScript.

Using the code

Adding JavaScript code in the HTML of the Web Form:

HTML
<script language=javascript>
  function RadioChecked(param)
  {
       { 
          var frm = document.forms[0];
          // Take all elements of the form
          for (i=0; i < frm.length; i++)
          {
            // itinerate the elements searching "RadioButtons"
            if (frm.elements[i].type == "radio")
            {
              // Unchecked if the RadioButton is != param
              if (param != frm.elements[i].id )
              {
                frm.elements[i].checked = false;
              }
            }
          }
      }
  }
</script>
<body MS_POSITIONING="GridLayout">
    <form id="Form1" method="post" runat="server">
        <asp:DataGrid id="countriesGrid" runat="server" 
                  DataKeyField="ID" AutoGenerateColumns="False">
            <Columns>
            <asp:TemplateColumn>
                <ItemTemplate>
                    <asp:RadioButton id="selectRadioButton" runat="server"  />
                <ItemTemplate>
            </asp:TemplateColumn>
            <asp:BoundColumn DataField="Code" 
                    HeaderText="Code" HeaderStyle-Font-Bold="True" />
            <asp:BoundColumn DataField="Country" 
                    HeaderText="Country" HeaderStyle-Font-Bold="True" />
            </Columns>
        </asp:DataGrid>
        <asp:Button id="Button1" runat="server" 
               Text="See Checked"></asp:Button>
    </form>
</body>

We should add the code shown below in the ItemDataBound event handler of the DataGrid:

VB
Private Sub countriesGrid_ItemDataBound(ByVal sender As Object, _
            ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) _
            Handles countriesGrid.ItemDataBound
    Select Case e.Item.ItemType
       // You can select the ItemType that you want
        Case ListItemType.AlternatingItem, _
                 ListItemType.Item, ListItemType.EditItem
            CType(e.Item.FindControl("selectRadioButton"), _
                RadioButton).Attributes.Add("onclick", _
                "javascript: RadioChecked('" + _
                CType(e.Item.FindControl("selectRadioButton"), _
                RadioButton).ClientID + "');")
    End Select
End Sub

If you want to see which country was selected, you must iterate the Items collection of the DataGrid control:

VB
Private Sub Button1_Click(ByVal sender As System.Object, _
            ByVal e As System.EventArgs) Handles Button1.Click
    Dim item As DataGridItem
    For Each item In dgCountries.Items
        Response.Write("Country : " + item.Cells(2).Text + " " + _
           CType(item.FindControl("selectRadioButton"), _
           RadioButton).Checked.ToString + vbnewline)
    Next
End Sub

Points of Interest

You can embed the JavaScript code in a .js file, so you can use it in future.

Tested on IE6, Netscape 7.0.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Argentina Argentina
My name is Hernan Molina. I'm a software developer from Buenos Aires, Argentina and I have been working in different IT projects for 7 years now. I'm also a Microsoft Certified Solution Developer in .NET. I'm interesting in everything related to .NET technology.

Comments and Discussions

 
QuestionWhat if the page is having other radio button also apart from datagrid Pin
_AK_21-Oct-08 1:09
_AK_21-Oct-08 1:09 
AnswerRe: What if the page is having other radio button also apart from datagrid Pin
Hernan Molina21-Oct-08 2:48
Hernan Molina21-Oct-08 2:48 
GeneralThanks for such a brilliant code Pin
sssassd6-Sep-07 3:05
sssassd6-Sep-07 3:05 
QuestionObject reference not set to an instance of an object Pin
netdeveloper12331-Jan-07 9:49
netdeveloper12331-Jan-07 9:49 
AnswerDISREGARD -- Re: Object reference not set to an instance of an object Pin
netdeveloper12331-Jan-07 10:35
netdeveloper12331-Jan-07 10:35 
GeneralAlternative not using javaScript Pin
funkrider15-May-05 11:35
funkrider15-May-05 11:35 
When I came up against the radio button issue when using a DataGrid / Repeater I opted to go old school and output the raw HTML for a radio button into a label contol. Of course you need to create an OnItemDataBound or OnItemCreated event to handle the formatting for your label contol.

By doing this you can manually configure the Value and the Name property for each radio button in the DataGrid. Something like this:
tmpLabel.Text = "<INPUT type=""radio"" value=""" & myValue & """ name=""RadioGroupName"">"


You can then pick up the value selected using:
Request.Form.Item("RadioGroupName")



GeneralRe: Alternative not using javaScript Pin
romias20-Sep-05 9:37
romias20-Sep-05 9:37 

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.