Tuesday, November 20, 2007

Selecting a single radio button inside a grid view

the below code will explain how to change your code for selecting a single radio button inside a grid view.

by default we can select multiple radio buttons inside a grid view.to make it a single selection we need to add a script..

below code explain that


  1 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CategoryID" DataMember="DefaultView" DataSourceID="SqlDataSource1"
  2 <Columns> 
  3 <asp:TemplateField> 
  4 <ItemTemplate> 
  5 <input type="radio" runat="server" id="rdOption" onclick="SelectOne(this,'GridView1')"  VALUE="rdo" /> 
  6 </ItemTemplate> 
  7 <HeaderStyle CssClass="Head" /> 
  8 <ItemStyle CssClass="Item" />
  9 </asp:TemplateField> 
 10
 11 <asp:BoundField DataField="CategoryID" HeaderText="CategoryID" InsertVisible="False" ReadOnly="True" SortExpression="CategoryID" > 
 12 <HeaderStyle CssClass="Head" /> 
 13 <ItemStyle CssClass="Item" /> 
 14 </asp:BoundField> 
 15
 16 <asp:BoundField DataField="CategoryName" HeaderText="CategoryName" SortExpression="CategoryName" > 
 17 <ItemStyle CssClass="Item" /> 
 18 <HeaderStyle CssClass="Head" /> 
 19 </asp:BoundField> 
 20 </Columns> 
 21 </asp:GridView>


add the following javascript

  1 <script language="javascript"
  2
  3 function SelectOne(rdo,gridName) 
  4
  5    all=document.getElementsByTagName("input"); 
  6    for(i=0;i<all.length;i++) 
  7    { 
  8      if(all[i].type=="radio"
  9      { 
 10         var count=all[i].name.indexOf(gridName+'$ctl' ); 
 11         if(count!=-1
 12         { 
 13            all[i].checked=false
 14         } 
 15       } 
 16     } 
 17    rdo.checked=true
 18
 19 </script>


the Script will be called in the on click event of the radio button in the grid

No comments: