IntroductionIn this article I will demonstration to how to validate whether to check at least one checkbox is checked in the Gridview in ASP.NET using JQuery. The JQuery is significant library to manipulate client html and css with less line of code.Before Jquery come up we have used the pure JavaScript to implement this features. I will give the JavaScript code as well in end of this article. ImplementationStep 1 As usual create a new web project using visual studio 2008 and give name to project is “CheckAtleastOne”. Note: you can use any name to project. Step 2 Add a GridView with few columns as like below, Html Code <asp:GridView ID="gvpub" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
Selection
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox runat="server" ID="chkSelection" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Address1" HeaderText="Address1" />
<asp:BoundField DataField="Address2" HeaderText="Country" />
<asp:BoundField DataField="Company" HeaderText="Company" />
</Columns>
</asp:GridView>The first column has a template field to customize the header and row for this column. The header template header is call Selection. The item template will have checkbox for represent each row. Finally add a submit button to perform the server side click event. When user click save button we will validate at least checkbox is checked or not if not check prompt message otherwise continue to server side task. Step 3 Let’s create a simple data source to bind to grid view. This data source is custom object collection of the publishers. Note: I have attached sample project end of this article you can download it. And also you can use any data source to bind GridView. C# Code using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class checkanduncheckdemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<Publisher> collectionOfPub = new List<Publisher>();
collectionOfPub.Add(new Publisher("Wrox", "No-02,John Ave 2", "US", "WROX"));
collectionOfPub.Add(new Publisher("Apress", "No-03,Cels Ave 6", "US", "APRESS"));
collectionOfPub.Add(new Publisher("Sams", "No-89,Test Ave 32", "US", "SAMS"));
collectionOfPub.Add(new Publisher("Orelly", "No-23/08,John Ave 23", "US", "ORELLY"));
collectionOfPub.Add(new Publisher("Packtpub", "No-56,John Ave 5", "INDIA", "PACKTPUB"));
this.gvpub.DataSource = collectionOfPub;
this.gvpub.DataBind();
}
}
}Run project and see the output as like below, Output Step 4 In order work with JQuery, we have to add JQuery library in page as like below, JavaScript <script language="javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js">
</script> Step 5 Now write few lines of JavaScript code to access checkbox controls within GridView with button click to implement features of this article aspiration. JavaScript <script language="javascript">
$(document).ready(function(){
$('#btnsave').click(function(){
var chkboxrowcount = $("#<%=gvpub.ClientID%> input[id*='chkSelection']:checkbox:checked").size();
if (chkboxrowcount==0)
{
alert("please select at least a record");
return false;
}
return true;
});
});
</script>Code Explanation1. As usual first line is declare document ready event 2. In the next line is register click event for save button in order validate checkbox when user click save button $('#btnsave').click(function(){ //code });3. Next line is important to get no of check box is checked within GridView. var chkboxrowcount = $("#<%=gvpub.ClientID%> input[id*='chkSelection']:checkbox:checked").size(); Two key points there in above line - "#<%=gvpub.ClientID%> input[id*='chkSelection']:checkbox its return all type input control is checkbox with ID contains chkSelection.
- …:checked").size(); is get number of checkbox is only checked.
4. Then check is count is check is 0 then at least one checkbox is not checked and prompt message and return false to prevent server side task. Otherwise continue perform the server side task. if (chkboxrowcount==0)
{
alert("please select at least a record");
return false;
}
return true;Now let’s give old model(pure javascript code to implement same features. Javascript function IsSelectedAtleastOneCheckBox()
{
var loTable=document.all("<%=gvpub.ClientID%>"); // GridView Name
count=0;
with(document.forms[0])
{
for(var i=0;i<elements.length;i++)
{
var e=elements[i];
if(e.type == "checkbox" && e.checked==true && e.id.substring(e.id.lastIndexOf('_')+1,e.id.length) == 'ControlName') // This is our control Name
{
count += 1;
}
}
}
if(count == 0)
{
alert("please select at least one ");
return false;
}
return true;
}
Then you have to call in this function for button as like below <asp:Button ID="btnsave" OnClientClick="return IsSelectedAtleastOneCheckBox();" runat="server"/>
So JQuery is best and less work to implement this kind of features than using pure JavaScript code. Now run application and try it. Live DemoCheck at least one checkbox Download Sample ProjectDownload source files -2 kb ConclusionIn this article you have learned how to validate to check whether at least checkbox is checked in GridView in asp.net using JQuery before process to server side task, I have given live demonstration, so you try it now here. Thank you for reading, hopes help, please posts your all comments. |