5,276,156 members and growing! (15,817 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, C#), Javascript, HTML, .NET (.NET, .NET 2.0), ASP.NET, Dev

Posted: 22 Jan 2008
Updated: 9 May 2008
Views: 24,489
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
31 votes for this Article.
Popularity: 5.45 Rating: 3.66 out of 5
5 votes, 16.1%
1
2 votes, 6.5%
2
1 vote, 3.2%
3
5 votes, 16.1%
4
18 votes, 58.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


Currently I'm working as a Sr. Software Engineer in SRM Techsol Pvt. Ltd., Lucknow, INDIA. I possess following degrees:

  • MCA from U.P. Technical University, Lucknow, INDIA.
  • PGDCA from Institute of Engineering and Rural Technology, Allahabad, INDIA.
  • BSc from University of Allahabad, Allahabad, INDIA.


Occupation: Software Developer (Senior)
Company: STPL
Location: India India

Other popular ASP.NET Controls articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 43 (Total in Forum: 43) (Refresh)FirstPrevNext
Subject  Author Date 
GeneralHow do I collect values for records with checkboxes selected server side?memberMember 34028866:00 1 Jul '08  
GeneralRe: How do I collect values for records with checkboxes selected server side?memberSAMir Nigam19:20 1 Jul '08  
GeneralRe: How do I collect values for records with checkboxes selected server side?memberMember 34028860:11 2 Jul '08  
GeneralRe: How do I collect values for records with checkboxes selected server side?memberSAMir Nigam0:24 2 Jul '08  
Questionif no click event then???memberMember 301315321:05 24 Jun '08  
AnswerRe: if no click event then???memberSAMir Nigam19:21 26 Jun '08  
GeneralWhat happens if checkboxes exists outside and inside of the grid?membersrinath g nath4:49 1 May '08  
GeneralRe: What happens if checkboxes exists outside and inside of the grid?member Samir Nigam 20:05 1 May '08  
QuestionChanges in case of Wizard Control??membersassyboy5:53 14 Feb '08  
AnswerRe: Changes in case of Wizard Control??member Samir Nigam 18:17 14 Feb '08  
GeneralRe: Changes in case of Wizard Control??membersassyboy22:39 14 Feb '08  
GeneralRe: Changes in case of Wizard Control??member SAMir Nigam 19:01 21 May '08  
GeneralNice onememberإ#1587م#1575ع#1610ل/codeProject$$>19:55 5 Feb '08  
GeneralRe: Nice one [modified]member Samir Nigam 21:42 5 Feb '08  
GeneralSecurity notificationmemberTuomas Hietanen5:01 30 Jan '08  
GeneralRe: Security notificationmember SAMir Nigam 19:02 21 May '08  
GeneralGreat WorkmemberGunarathinam18:47 29 Jan '08  
GeneralRe: Great WorkmemberSamir Nigam20:14 29 Jan '08  
GeneralVery goodmemberDNhan3:00 29 Jan '08  
GeneralRe: Very goodmemberSamir Nigam3:08 29 Jan '08  
GeneralNice conceptmemberjoohitha2:18 29 Jan '08  
GeneralRe: Nice conceptmemberSamir Nigam3:06 29 Jan '08  
GeneralVery Nice ConceptmemberSandeep Shekhar20:02 27 Jan '08  
GeneralRe: Very Nice ConceptmemberSamir Nigam21:42 27 Jan '08  
Generalgood workmemberAbhijit Jana22:27 24 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-2008
Web08 | Advertise on the Code Project