Click here to Skip to main content
6,595,444 members and growing! (19,658 online)
Email Password   helpLost your password?
Web Development » ASP.NET Controls » Grid Controls     Intermediate License: The Code Project Open License (CPOL)

Client-Side Validation for the CheckBoxes Inside a GridView

By Samir NIGAM

This article describes how to count the selected checkboxes inside a GridView control.
C# (C# 2.0), Javascript, HTML, .NET (.NET 2.0), ASP.NET, Dev
Posted:22 Jan 2008
Updated:9 May 2008
Views:60,655
Bookmarked:58 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
35 votes for this article.
Popularity: 5.60 Rating: 3.63 out of 5
6 votes, 17.1%
1
2 votes, 5.7%
2
1 vote, 2.9%
3
6 votes, 17.1%
4
20 votes, 57.1%
5

demo.gif

Introduction

I am presenting here a JavaScript code that ensures that at least one checkbox is checked among the checkboxes in a particular column inside a GridView control before submitting a form.

Using the code

I have used a TemplateField inside the GridView and put a CheckBox in the ItemTemplate of the TemplateField.

The HTML code looks like this:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
   <Columns> 
      <asp:BoundField HeaderText="n" DataField="sno"> 
       <HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="50px" />
          <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
      </asp:BoundField>                
       <asp:TemplateField HeaderText="Select">
            <ItemTemplate>
               <asp:CheckBox ID="chkBxSelect" runat="server" />
            </ItemTemplate>
            <HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" />
            <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
        </asp:TemplateField>
     </Columns>
  </asp:GridView>
 <asp:Button ID="btnPost" runat="server" Text="Post" 
             OnClientClick="javascript:return TestCheckBox();"
             OnClick="btnPost_Click" />

Attach a OnClientClick event to the button [btnPost]:

<asp:Button ID="btnPost" runat="server" Text="Post" 
            OnClientClick="javascript:return TestCheckBox();"
            OnClick="btnPost_Click" />

Add this JavaScript in the page’s head section:

<script type="text/javascript">
   var TargetBaseControl = null;
        
   window.onload = function()
   {
      try
      {
         //get target base control.
         TargetBaseControl = 
           document.getElementById('<%= this.GridView1.ClientID %>');
      }
      catch(err)
      {
         TargetBaseControl = null;
      }
   }
        
   function TestCheckBox()
   {              
      if(TargetBaseControl == null) return false;
      
      //get target child control.
      var TargetChildControl = "chkBxSelect";
            
      //get all the control of the type INPUT in the base control.
      var Inputs = TargetBaseControl.getElementsByTagName("input"); 
            
      for(var n = 0; n < Inputs.length; ++n)
         if(Inputs[n].type == 'checkbox' && 
            Inputs[n].id.indexOf(TargetChildControl,0) >= 0 && 
            Inputs[n].checked)
          return true;        
            
      alert('Select at least one checkbox!');
      return false;
   }
</script>

In the above script, the global variable TargetBaseControl has been initialized in the window.onload event in order to get the reference of the parent control [GridView]. The function TestCheckBox first gets the array of all ‘input’elements inside the parent control. After that, it iterates all the elements of the array and tests a condition, and if the condition is found to be true, it returns true indicating that at least one checkbox is checked inside the GridView; else it displays a message and returns false. The condition tests the elements of a specific type in a particular column inside the parent element.

Just download the sample application and enjoy coding! I hope you will like this article.

Features of this script

This script is cross-browser compatible and fast as it iterates elements of a specific tag inside a target element [GridView] rather than iterating in a whole form. It searches the elements of a specific type in a particular column of the target element [GridView].

Supporting browsers

I have tested this script on the following browsers:

Browsers.png

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Samir NIGAM


Member

SAMIR NIGAM is the Tech Lead at Axero Solutions LLC. He is a CodeProject MVP 2009, a Microsoft Certified Technology
Specialist (MCTS)
as well as a Microsoft Certified Professional Developer (MCPD)
in C# for web-based applications. He is an insightful IT professional with
results-driven comprehensive technical skill having rich, hands-on work experience
in web-based applications using ASP.NET, C#, AJAX, Microsoft
Enterprise Library
, MS SQL Server 2005.


He has earned his master degree (MCA) from U.P. Technical University, Lucknow,
INDIA, his post graduate dipoma (PGDCA ) from Institute of Engineering and
Rural Technology, Allahabad, INDIA and his bachelor degree (BSc - Mathematics)
from University of Allahabad, Allahabad, INDIA.


He has good knowledge of Object Oriented Programming, 3-Tier Architecture
and Algorithm Analysis & Design as well as good command over cross-browser
client side programming using JavaScript.

Awards:


Contact: nigam.samir@hotmail.com
Occupation: Team Leader
Company: Axero Solutions LLC
Location: India India

Other popular ASP.NET Controls articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 45 (Total in Forum: 45) (Refresh)FirstPrevNext
GeneralClient-Side Validation for the CheckBoxes Inside a GridView Pinmembersaiprasada1:25 26 May '09  
GeneralReally Nice PinmemberMember 38915462:45 16 Oct '08  
GeneralHow do I collect values for records with checkboxes selected server side? PinmemberMember 34028866:00 1 Jul '08  
GeneralRe: How do I collect values for records with checkboxes selected server side? PinmemberSAMir Nigam19:20 1 Jul '08  
GeneralRe: How do I collect values for records with checkboxes selected server side? PinmemberMember 34028860:11 2 Jul '08  
GeneralRe: How do I collect values for records with checkboxes selected server side? PinmemberSAMir Nigam0:24 2 Jul '08  
Questionif no click event then??? PinmemberMember 301315321:05 24 Jun '08  
AnswerRe: if no click event then??? PinmemberSAMir Nigam19:21 26 Jun '08  
GeneralWhat happens if checkboxes exists outside and inside of the grid? Pinmembersrinath g nath4:49 1 May '08  
GeneralRe: What happens if checkboxes exists outside and inside of the grid? Pinmember Samir Nigam 20:05 1 May '08  
QuestionChanges in case of Wizard Control?? Pinmembersassyboy5:53 14 Feb '08  
AnswerRe: Changes in case of Wizard Control?? Pinmember Samir Nigam 18:17 14 Feb '08  
GeneralRe: Changes in case of Wizard Control?? Pinmembersassyboy22:39 14 Feb '08  
GeneralRe: Changes in case of Wizard Control?? Pinmember SAMir Nigam 19:01 21 May '08  
GeneralNice one Pinmemberإ#1587م#1575ع#1610ل/codeProject$$>19:55 5 Feb '08  
GeneralRe: Nice one [modified] Pinmember Samir Nigam 21:42 5 Feb '08  
GeneralSecurity notification PinmemberTuomas Hietanen5:01 30 Jan '08  
GeneralRe: Security notification Pinmember SAMir Nigam 19:02 21 May '08  
GeneralGreat Work PinmemberGunarathinam18:47 29 Jan '08  
GeneralRe: Great Work PinmemberSamir Nigam20:14 29 Jan '08  
GeneralVery good PinmemberDNhan3:00 29 Jan '08  
GeneralRe: Very good PinmemberSamir Nigam3:08 29 Jan '08  
GeneralNice concept Pinmemberjoohitha2:18 29 Jan '08  
GeneralRe: Nice concept PinmemberSamir Nigam3:06 29 Jan '08  
GeneralVery Nice Concept PinmemberSandeep Shekhar20:02 27 Jan '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 9 May 2008
Editor: Smitha Vijayan
Copyright 2008 by Samir NIGAM
Everything else Copyright © CodeProject, 1999-2009
Web18 | Advertise on the Code Project