65.9K
CodeProject is changing. Read more.
Home

DATAGRID WITH RADIO BUTTON AND SINGLE SELECTION

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.61/5 (8 votes)

Nov 9, 2006

CPOL
viewsIcon

73361

downloadIcon

106

This article helps in creating a Data Grid with radio button and allows single selection.

Introduction

Placing Radio Button in the row items of Data grid which allows only one of the radio buttons to be selected at a time in Web applications is a well known problem. I came across many solutions, such as, making a custom data grid which allows the "id" property of its child control to be changed or I even found some free "RowSelector" controls available which allow single radio button selection in the data grid. But these solutions provide much of a processing overhead or are complex. I thought that any solution using some JavaScript to accomplish this task would be of great use.

The JavaScript code below will allow accomplishing the intended task of single select of radio button inside a data grid.

<script  language="javascript">
function SelectOne(rdo,gridName)
{
/* Getting an array of all the "INPUT" controls on the form.*/
all=document.getElementsByTagName("input");
 for(i=0;i<all.length;i++)
 {
  if(all[i].type=="radio")/*Checking if it is a radio button*/
  {
/*I have added '__ctl' ASP.NET adds '__ctl' to all 
    the controls of DataGrid.*/
   var count=all[i].id.indexOf(gridName+'__ctl'); 
   if(count!=-1)
   {
    all[i].checked=false;
   }
  }
 }
 rdo.checked=true;/* Finally making the clicked radio button CHECKED */
}
</script>

Below is the DataGrid:

<table width="100%">
 <tr>
     <td align="center">
    <b>
        <u>DATAGRID WITH RADIO BUTTON AND SINGLE SELECTION</u>
    </b>
     </td>
 </tr>
    <tr>
     <td align="center">
      <asp:DataGrid Runat="server" ID="dg" AutoGenerateColumns="False"
     BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px"
    BackColor="White" CellPadding="4" 
    OnItemDataBound="dg_onItemDataBound"
    OnPageIndexChanged="dg_onPageIndexChanged" PageSize="5"
    AllowPaging="True" GridLines="None" Width="25%">
       <FooterStyle ForeColor="#330099" BackColor="#FFFFCC"></FooterStyle>
       <SelectedItemStyle Font-Bold="True"
    ForeColor="#663399" BackColor="#FFCC66"/>
       <ItemStyle ForeColor="#330099" BackColor="White"></ItemStyle>
       <HeaderStyle Font-Bold="True" ForeColor="#FFFFCC"
     BackColor="#990000"/>
       <Columns>
        <asp:TemplateColumn>
         <ItemTemplate>
          <input type="radio" runat="server" id="rdo" 
        onclick="SelectOne(this,'dg')" VALUE="rdo" />
     </ItemTemplate>
        </asp:TemplateColumn>
        <asp:BoundColumn DataField="_Id" HeaderText="Id"/>
        <asp:BoundColumn DataField="_Name" HeaderText="Name"/>
       </Columns>
       <PagerStyle HorizontalAlign="Center" 
    ForeColor="#330099" BackColor="#FFFFCC"/>
      </asp:DataGrid>
  </td>
 </tr>
</table>
Happy Reading :)