CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
GridView with RadioButton – Select One Row at a Time

By Bala Murugan
Posted On Sep 21,2008
Article Rating:
Be first to rate
this article.
No of Comments: 23
Category: ASP.Net
Print this article.

GridView with RadioButton – Select One at a Time

 

Introduction

Sometimes, we will have requirements to have a RadioButton control in every row of the GridView control to select one row at a time. If we have a TemplateColumn with a RadioButton control, it will allow selection of multiple rows by default. This is because, the RadioButton will have different ID for every row and hence it will allow multiple selections. So, we should add some sort of client side functionality that prevents selection of multiple Radio Buttons but one. In this article, we will call a Javascript function on click of RadioButton that checks if there is some other RadioButton in the GridView is already selected to uncheck it leaving the current selection.

 

Steps

Declare a GridView control with a TemplateColumn as the first column to include Radio control. Include BoundField for other fields to display in the GridView.

 

<asp:GridView ID="gvUsers" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#010101" BorderStyle="Groove" BorderWidth="1px" CellPadding="4" OnRowCommand="gvUsers_RowCommand">

         <Columns>

            <asp:TemplateField HeaderText="Select">

                  <ItemTemplate>

                     <asp:RadioButton ID="rdbGVRow" onclick="javascript:CheckOtherIsCheckedByGVID(this);"  runat="server" />

                  </ItemTemplate>

            </asp:TemplateField>

            <asp:BoundField DataField="Email" HeaderText="Email" ReadOnly="True" />

            <asp:BoundField DataField="FirstName" HeaderText="First Name" ReadOnly="True" />

            <asp:BoundField DataField="LastName" HeaderText="Last Name" ReadOnly="True" />                        

      </Columns>

   <FooterStyle BackColor="White" ForeColor="#330099" />

   <RowStyle BackColor="White" ForeColor="#330099" />

                    <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />

   <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />

  <HeaderStyle BackColor="#F06300" Font-Bold="True" ForeColor="#FFFFCC" />

</asp:GridView>

 

CodeBehind

protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

            BindUsers();

    }

    public void BindUsers()

    {

        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Sql"].ConnectionString);

        con.Open();

        SqlCommand com = new SqlCommand("SP_GetUsersForModeration", con);

        com.CommandType = CommandType.StoredProcedure;

        SqlDataAdapter ada = new SqlDataAdapter(com);

        DataTable dt = new DataTable();

        ada.Fill(dt);       

        gvUsers.DataSource = dt;

        gvUsers.DataBind();

    }

 

Execute the page. You can see the GridView with RadioButton.

 

 

Adding Client Side Functionality

To check if there is some other row selected and to uncheck it by keeping the current row selection we will call a JavaScript function called CheckOtherIsCheckedByGVID(). This function is called by the OnClick event of the RadioButton, Refer the above code.

The below JavaScript function will do our client side functionality.

 

function CheckOtherIsCheckedByGVID(spanChk)

       {            

           var IsChecked = spanChk.checked;        

           if(IsChecked)

              {

               spanChk.parentElement.parentElement.style.backgroundColor='#228b22'; 

               spanChk.parentElement.parentElement.style.color='white';

              }                   

             

           var CurrentRdbID = spanChk.id;   

           var Chk = spanChk;

              Parent = document.getElementById('gvUsers');          

              var items = Parent.getElementsByTagName('input');            

             

              for(i=0;i<items.length;i++)

              {               

                  if(items[i].id != CurrentRdbID && items[i].type=="radio")

                  {           

                      if(items[i].checked)

                      {    

                          items[i].checked = false;

items[i].parentElement.parentElement.style.backgroundColor='white';

items[i].parentElement.parentElement.style.color='black';                     }

                  }

              }

       }

 




Execute the page and see it in action.

 

Since, we are getting all the elements with tag name as “input”, the above code will uncheck if there are any other RadioButton control is present in any other column for a different purpose. To understand it better, include one more TemplateField with RadioButton control at the last in the GridView columns list and test it.

To handle the above scenario with multiple RadioButton in a Row, we will change the code a bit to access the RadioButton based on the column location. If we see the rendered table in the HTML output, we will have the RadioButton at every first TD. The below code will clear the selection of RadioButton that is found only in the first column.

 

  function CheckOtherIsCheckedByGVIDMore(spanChk)

       {

           var IsChecked = spanChk.checked;

           if(IsChecked)

              {

               spanChk.parentElement.parentElement.style.backgroundColor='#228b22'; 

               spanChk.parentElement.parentElement.style.color='white';

              }                   

           var CurrentRdbID = spanChk.id;   

           var Chk = spanChk;           

              Parent = document.getElementById('gvUsers');                        

              for(i=0;i< Parent.rows.length;i++)

              {

                  var tr = Parent.rows[i];

                  var td = tr.childNodes[0];             

                  var item =  td.firstChild;            

                  if(item.id != CurrentRdbID && item.type=="radio")

                  {           

                      if(item.checked)

                      {    

                          item.checked = false;

                          item.parentElement.parentElement.style.backgroundColor='white';

                          item.parentElement.parentElement.style.color='black';

                      }

                  }

              }

       }

 

 

The above code assumes the RadioButton will be the first column of every row in the GridView.

 

This code will work perfectly even if there are RadioButton present in any other column of the GridView control.

 

Download Source

Source Code 


Conclusion

Using CheckBox control to enable selection of a single row and selection of all the rows is a common task that we will do GridView control. This article will help you doing the same with JavaScript in client side. Download the source attached with this article. Thanks for reading this article.

Read my previous article, GridView with CheckBox – Select All and Highlight Selected Row. Muhammed Mosa gave a useful comment to rewrite the javascript codes using JQuery which will reduce the code and increase performance. I will re-write both the article and post it in future using JQuery.

 

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
Jaggiriya codes are working fine
Hi Jaggiriya, your codes are working fine. thanks.
but the gridview's clientIDMode must be set to Predictable.
error
after ran your project, it has the following message:
"javascript runtime error: id undefined or null"
Work All Browser
function CheckOtherIsCheckedByGVID(spanChk)
{
var IsChecked = spanChk.checked;
var CurrentRdbID = spanChk.id;
Parent = document.getElementById('<%= gvUsers.ClientID%>');
for (i = 0; i < Parent.rows.length - 1; i++)
{

var tr = Parent.rows[i];
var td = tr.childNodes[0];

if (document.getElementById('<%= gvUsers.ClientID%>_rdbGVRow_' + i).checked && CurrentRdbID != ('<%= gvUsers.ClientID%>_rdbGVRow_' + i))
document.getElementById('<%= gvUsers.ClientID%>_rdbGVRow_' + i).checked = false;
}
}
best helper
thanks for easy functionality....
Thanks A lot
Thanks a lot for all the explanaition and of course for your code, it works very good. :D
IE9
This only seem to work in EI9 Compatability mode. Anybody find a work around for the new rendering in IE9?
Better Method
There is a metter Method.
Use this in template field

<ItemTemplate>
<input name="radioSelector" type="radio" value='<%# Eval("ID") %>' />
</ItemTemplate>

On postback enumerate the grid to find the selected checkbox.


foreach (GridViewRow row in this.gridview.Rows)
{
CheckBox cbx = (CheckBox)row.FindControl("cbxSelect");

if (cbx.Checked)
{
//Do Something
}
}
Not Working
This article is working fine in ie8 and chrome but not working in Mozilla Firefox.
GridView
cool, how I can use gvUsers_RowCommand function because I want to update the table in database please
Thanks..
Worked really well.. Thank you..
Thnx ..
Thanx a lot..
Great Work
Great Work Done....Thanks a lot
Using two gridviews
Hi,
Its working perfectly fine with in one gridview but if we use two gridviews differently in the same page.How can we handle by using the same script
Solution
Its is true just change the property parentElement to parentNode and it worked.
hey you can use it on master page as well need to pass gridview id. I modify the code according to my requirement

function CheckOtherIsCheckedByGVID(grd, spanChk) {
var IsChecked = spanChk.checked;
if (IsChecked) {
// spanChk.parentElement.parentElement.style.backgroundColor = '#228b22';
//spanChk.parentElement.parentElement.style.color = 'white';
spanChk.parentNode.parentNode.style.backgroundColor = '#228b22';
spanChk.parentNode.parentNode.style.color = 'white';

}

var CurrentRdbID = spanChk.id;
var Chk = spanChk;
Parent = document.getElementById(grd);
var items = Parent.getElementsByTagName('input');

for (i = 0; i < items.length; i++) {
if (items[i].id != CurrentRdbID && items[i].type == "radio") {
if (items[i].checked) {
items[i].checked = false;

// items[i].parentElement.parentElement.style.backgroundColor = 'white';
// items[i].parentElement.parentElement.style.color = 'black';
items[i].parentNode.parentNode.style.backgroundColor = 'white';
items[i].parentNode.parentNode.style.color = 'black';
}
}
}
}
Only work in IE....
Hi guy this code works fine in IE but not work in other browser do you have any solution to solve it.Problem is in
var tr = Parent.rows[i];

var td = tr.childNodes[0];

var item = td.firstChild;
its not catch item.firstchild value. it goes null in firefox. please find solution and rply on my email id.

thanks
Umang Soni
[umangjsoni@gmail.com]
Nothing is Impossible
Hey Working fine with all Browsers

Thanks
Solution
To work in firefox, IE, Chrome, change the property parentElement to parentNode
Problem with firefox
Javascript working fine in IE But not in firfox
Does not work in Mozilla
The code is working superbly in Internet Explorer, but it is totally failing in Mozilla 3.0. can you please tell me what is the reason and solution to it.
Does not work in Mozilla
Hi,

The code is working superbly in Internet Explorer, but it is totally failing in Mozilla 3.0. can you please tell me what is the reason and solution to it.

Thanks
Great !!!
Simple and great logic and code. Thanks
Re: Great Code
It will work, just modify following line :

from :
Parent = document.getElementById('gvUsers');

to:
Parent = document.getElementById('<%= gvUsers.ClientID %>');

Great Code
Great code but the Javascript function does not work with Master Pages. I need to figure out how to alter the javascript to work.

Thank you