Using Radio Button in GridView With JavaScript Validation

In this article you will learn how to use a radio button in a GridView with JavaScript validation.

Introduction

A developer is asking how to select one radio button at a time if the radio button is inside the GridView. As you may know setting the group name attribute of a radio button will not work if the radio button is located within a data representation control like a GridView. This is because the radio button inside a GridView behaves differently. Since a GridView is rendered as a table element, at run time it will assign a different "name" to each radio button. Hence you are able to select multiple rows.

In this article I'm going to show how to select one radio button at a time in GridView and add a simple validation to it using plain JavaScript. To get started let's go ahead and fire up Visual Studio and then create a new web application / website project. Add a WebForm and then grab GridView. The mark up would look something like this:

  1. <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" >  
  2.         <Columns>  
  3.             <asp:TemplateField>  
  4.                 <ItemTemplate>  
  5.                    <asp:RadioButton ID="rb" runat="server" />  
  6.                 </ItemTemplate>  
  7.             </asp:TemplateField>  
  8.             <asp:BoundField DataField="RowNumber" HeaderText="Row Number" />  
  9.             <asp:BoundField DataField="Col1" HeaderText="First Column" />  
  10.             <asp:BoundField DataField="Col2" HeaderText="Second Column" />  
  11.         </Columns>  
  12. </asp:GridView>  
If you notice I've added a templatefield column so that we can add the radio button there. Also I have set up some BoundField columns and set the DataFields as RowNumber, Col1 and Col2. These columns are just dummy columns and are used for the simplicity of this example. Now where do these columns come from? These columns are created by hand at the code behind file of the ASPX. Here's the code below:
  1. private DataTable FillData()  
  2. {  
  3.     DataTable dt = new DataTable();  
  4.     DataRow dr = null;  
  5.   
  6.     //Create DataTable columns  
  7.     dt.Columns.Add(new DataColumn("RowNumber"typeof(string)));  
  8.     dt.Columns.Add(new DataColumn("Col1"typeof(string)));  
  9.     dt.Columns.Add(new DataColumn("Col2"typeof(string)));  
  10.   
  11.     //Create Row for each columns  
  12.     dr = dt.NewRow();  
  13.     dr["RowNumber"] = 1;  
  14.     dr["Col1"] = "A";  
  15.     dr["Col2"] = "B";  
  16.     dt.Rows.Add(dr);  
  17.   
  18.     dr = dt.NewRow();  
  19.     dr["RowNumber"] = 2;  
  20.     dr["Col1"] = "AA";  
  21.     dr["Col2"] = "BB";  
  22.     dt.Rows.Add(dr);  
  23.   
  24.     dr = dt.NewRow();  
  25.     dr["RowNumber"] = 3;  
  26.     dr["Col1"] = "A";  
  27.     dr["Col2"] = "B";  
  28.     dt.Rows.Add(dr);  
  29.   
  30.     dr = dt.NewRow();  
  31.     dr["RowNumber"] = 4;  
  32.     dr["Col1"] = "A";  
  33.     dr["Col2"] = "B";  
  34.     dt.Rows.Add(dr);  
  35.   
  36.     dr = dt.NewRow();  
  37.     dr["RowNumber"] = 5;  
  38.     dr["Col1"] = "A";  
  39.     dr["Col2"] = "B";  
  40.     dt.Rows.Add(dr);  
  41.   
  42.     return dt;  
  43. }  
And here's the code for binding the GridView with the dummy data above.
  1. protected void Page_Load(object sender, EventArgs e)  
  2.  {  
  3.     if (!IsPostBack)  
  4.     {  
  5.        GridView1.DataSource = FillData();  
  6.        GridView1.DataBind();  
  7.     }  
  8. }  
As simple as that, we now have a GridView data with a radio button on each row. Now let's go ahead and switch back to ASPX mark up. In this example I'm going to use a JavaScript for validating the radio button to select one radio button at a time. (You could also use jQuery to take advantage of the jQuery selectors for easy DOM manipulation.) Here's the JavaScript code below:
  1. function CheckOtherIsCheckedByGVID(rb)   
  2. {  
  3.     var isChecked = rb.checked;  
  4.     var row = rb.parentNode.parentNode;  
  5.     if (isChecked)   
  6.     {  
  7.         row.style.backgroundColor = '#B6C4DE';  
  8.         row.style.color = 'black';  
  9.     }  
  10.     var currentRdbID = rb.id;  
  11.     parent = document.getElementById("<%= GridView1.ClientID %>");  
  12.     var items = parent.getElementsByTagName('input');  
  13.   
  14.     for (i = 0; i < items.length; i++)  
  15.     {  
  16.         if (items[i].id != currentRdbID && items[i].type == "radio")   
  17.         {  
  18.             if (items[i].checked)  
  19.             {  
  20.                 items[i].checked = false;  
  21.                 items[i].parentNode.parentNode.style.backgroundColor = 'white';  
  22.                 items[i].parentNode.parentNode.style.color = '#696969';  
  23.             }  
  24.         }  
  25.     }  
  26. }  
The function above sets the row of the current selected radio button's style to determine that the row is selected and then loops through the radio buttons in the GridView, de-select the previous selected radio button and set the row style back to its default. The next thing is to call the JavaScript function above in the onclick event of the radio button as in the following:
  1. <asp:RadioButton ID="rb" runat="server" onclick="javascript:CheckOtherIsCheckedByGVID(this);" />  
Here's the output below:

On Load:



After selecting a Radio Button:



As you can see, on initial load there's no default selected radio in the GridView. Now let's add a simple validation for that. We will basically display an error message if a user clicks a button that triggers a postback without selecting a radio button in the GridView. Here's the JavaScript for the validation:

  1. unction ValidateRadioButton(sender, args)   
  2. {  
  3.     var gv = document.getElementById("<%= GridView1.ClientID %>");  
  4.     var items = gv.getElementsByTagName('input');  
  5.     for (var i = 0; i < items.length; i++)   
  6.     {  
  7.         if (items[i].type == "radio")   
  8.         {  
  9.             if (items[i].checked)   
  10.             {  
  11.                 args.IsValid = true;  
  12.                 return;  
  13.             }  
  14.             else   
  15.             {  
  16.                 args.IsValid = false;  
  17.             }  
  18.         }  
  19.     }  
  20. }  
The function above loops through the rows in GridView and find all the radio buttons within it. It will then check each radio button's checked property. If a radio is checked then set IsValid to true else set it to false. The reason why I'm using IsValid is because I'm using the ASP validator control for validation. Now add the following markup below under the GridView declaration:
  1. <br />  
  2. <asp:Label ID="lblMessage" runat="server" />  
  3. <br />  
  4. <asp:Button ID="btn" runat="server" Text="POST" onclick="btn_Click" ValidationGroup="GroupA" />  
  5. <asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Please select row in the grid." ClientValidationFunction="ValidateRadioButton" ValidationGroup="GroupA" style="display:none"></asp:CustomValidator>  
  6. <asp:ValidationSummary ID="ValidationSummary1" runat="server" ValidationGroup="GroupA" HeaderText="Error List:" DisplayMode="BulletList" ForeColor="Red" />  
And then at Button Click event add this simple code below just to test if the validation works:
  1. protected void btn_Click(object sender, EventArgs e)   
  2. {  
  3.    lblMessage.Text = "Postback at: " + DateTime.Now.ToString("hh:mm:ss tt");  
  4. }  

Running the page will show something as in the following in the browser.

When validation triggers

 
 
When successful
 
 

That's it! I hope you find this article useful.