Click here to Skip to main content
Click here to Skip to main content

Handling RadioButtons on DataGrid

, 6 May 2005
Rate this:
Please Sign up or sign in to vote.
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:

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

    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:

    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

Share

About the Author

Hernan Molina
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 PinmemberApurva Kaushal21-Oct-08 1:09 
AnswerRe: What if the page is having other radio button also apart from datagrid PinmemberHernan Molina21-Oct-08 2:48 
GeneralThanks for such a brilliant code Pinmembersssassd6-Sep-07 3:05 
QuestionObject reference not set to an instance of an object Pinmembernetdeveloper12331-Jan-07 9:49 
AnswerDISREGARD -- Re: Object reference not set to an instance of an object Pinmembernetdeveloper12331-Jan-07 10:35 
GeneralAlternative not using javaScript Pinmemberfunkrider15-May-05 11:35 
GeneralRe: Alternative not using javaScript Pinmemberromias20-Sep-05 9:37 

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 | Mobile
Web01 | 2.8.140827.1 | Last Updated 6 May 2005
Article Copyright 2005 by Hernan Molina
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid