Single selection of checkbox in gridview


In this article I am going to explain you how to make a single selection check box inside Gridview. When the checkbox is selected automatically previously selected checkbox will be deselected, using javascript function.

In this article I am going to explain you how to make a single selection check box inside Gridview. When the checkbox is selected automatically previously selected checkbox will be deselected, using javascript function.

Here we will be using gridview with itemtemplate column with checkboxes in asp.net 4.0. Gridview is bound by fetching data from database.
When one checkbox is selected from Gridview automatically previously selected checkbox will be deselected, using javascript function

Below is the .ASPX code


<body>
<form id="form1" runat="server">
<div>
<table width="1000px" align="center">
<tr>

<td align="center">
<asp:GridView ID="GridView1" runat="server" DataKeyNames="uhidno" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField>

<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" onclick ="CheckOne(this)"/>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="uhidno" HeaderText="MemberName"/>
<asp:BoundField DataField="FirstName" HeaderText="MemberName"/>
</Columns>
</asp:GridView>
</td>

</tr>

<<tr>

<td align="center">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
< asp:Button ID="Button1" runat="server" Text="Button" / >
</td>

</tr>
</table>
</div>
</form>
</body>
</html>



--javascript code to select the single checkbox, when other check box is selected
automatically the previously selected checkbox will be deselected


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script language="javascript" type="text/javascript">
function CheckOne(obj) {
var grid = obj.parentNode.parentNode.parentNode;
var inputs = grid.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "checkbox") {
if (obj.checked && inputs[i] != obj && inputs[i].checked) {
inputs[i].checked = false;
}
}
}
}

< /script >
</head>


Comments

Author: DeviPriyaa04 Jan 2012 Member Level: Gold   Points : 0

hi,

Use Radio button instead of check box
and set "GroupName" property for Radio button



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: