Bind Radio Button in Grid View.

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="MyUserGrid" 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["ConString"].ConnectionString);
        con.Open();
        SqlDataAdapter ada = new SqlDataAdapter("select EmployeeId, TitleOfCourtesy, FirstName,BirthDate from employees",con);
        DataSet DS = new DataSet();
        ada.Fill(DS);
        gvUsers.DataSource = DS;
        gvUsers.DataBind();
    }
 
 
WebConfig
 
under  configuration :
 
<
connectionStrings>
 <add name="ConString" connectionString="uid=sa;pwd=;database=NorthWind;server=RajeshI" providerName="System.Data.SqlClient"/>
</connectionStrings>

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;
      var CurrentRdbID = spanChk.id;
      var Chk = spanChk;
      Parent = document.getElementById('<%=MyUserGrid.ClientID %>');
      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;
           }
         }
     }
}

 
 

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('<%=MyUserGrid.ClientID %>');

              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.

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.

Javascript working fine in IE But not Some time in firfox .To work in firefox, IE, Chrome, change the property parentElement to parentNode.

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites