Check One CheckBox To Check All CheckBoxes

All the rows in a DataGrid, including the Header, are accompanied with a CheckBox. I want that when the CheckBox in the Header is checked, then all the CheckBoxes should automatically get checked. I set the AutoPostBack property of the CheckBox in the Header to True & am invoking a sub named CheckAllRows on the CheckedChanged event of this CheckBox. The CheckBox in the Header exists within the HeaderTemplate of a TemplateColumn in the DataGrid & the rest of the CheckBoxes reside within the ItemTemplate of the same TemplateColumn. This is the code (the ID of the CheckBox in the Header is chkHeader & the IDs of the rest of the CheckBoxes are chkItem):

Sub CheckAllRows(ByVal obj As Object, ByVal ea As EventArgs)
    Dim chkAllRows As CheckBox
    Dim chkSelHeader As CheckBox
    Dim dgItem As DataGridItem

    For Each dgItem In dg1.Items
        If (dgItem.ItemType = ListItemType.Header) Then
            chkSelHeader = dgItem.FindControl("chkHeader")
            Response.Write("hello<br>")
            If (chkSelHeader.Checked) Then
                If (dgItem.ItemType = ListItemType.Item Or dgItem.ItemType = ListItemType.AlternatingItem) Then
                    chkAllRows = dgItem.FindControl("chkItem")
                    chkAllRows.Checked = True
                End If
            End If
        End If
    Next
End Sub


Now when I check the CheckBox in the Header, then the page posts but none of the CheckBoxes apart from the CheckBox in the Header get checked. Also notice the Response.Write("hello<br>") line which is within the first If condition. Even that line doesn't get executed since after post back, the page doesn't display the text hello.

What am I doing wrong here?

Thanks

RON
*********
If you have an apple & I have an apple & we exchange our apples, then each of us will still have only 1 apple but if you have an idea & I have an idea & we exchange our ideas, then each of us will have 2 ideas
0
RN5A
12/4/2006 11:15:53 AM
asp.net.getting-started 91979 articles. 3 followers. Follow

7 Replies
962 Views

Similar Articles

[PageSpeed] 10

Hi RN5A,

I had to do like what you want to do, this is my solution:

create a new javascript file with this function in it:

 function SelectAllCheckBoxes(spanChk){
   // Added as ASPX uses SPAN for checkbox
   var oItem = spanChk.children;
   var theBox= (spanChk.type=="checkbox") ? 
        spanChk : spanChk.children.item[0];
   xState=theBox.checked;
   elm=theBox.form.elements;

   for(i=0;iif(elm[i].type=="checkbox" && 
              elm[i].id!=theBox.id)
     {
       //elm[i].click();
       if(elm[i].checked!=xState)
         elm[i].click();
       //elm[i].checked=xState;
     }
 }

 and then in the page_load method you register the javascript:

    protected void Page_Load(object sender, EventArgs e)
    {
        // Register the javascript for checking (and unchecking) all checkboxes
        ClientScript.RegisterClientScriptInclude("SelectAllCheckboxes", "./js/checkboxgridview.js");
    }

 in the GridView you create a header with a checkbox that execute the javascript function:

        <asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="Black"
            BorderStyle="None" BorderWidth="1px" CellPadding="3" CaptionAlign="Left" OnRowDataBound="GridView1_RowDataBound">
            <Columns>
                <asp:TemplateField>
                    <HeaderTemplate>
                        <input id="CheckAll" onclick="javascript:SelectAllCheckBoxes(this);" runat="server"
                            type="checkbox" />
                    </HeaderTemplate>
                    <ItemTemplate>
                        <asp:CheckBox ID="CheckBoxRow" runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
 

 

I think this solution is better than with postback, because you don't have to wait for the page being refreshed everytime you click on the "all" checkbox.

Hope this helps. :)

0
ThienZ
12/4/2006 12:34:36 PM
What I find is if I get rid of the first If condition which checks whether the ItemType is Header or not i.e. this line

If (dgItem.ItemType = ListItemType.Header) Then

& modify the For...Next loop in the sub named CheckAllRows like this

On Error Resume Next
For Each dgItem In dgMarks.Items
    chkSelHeader = dgItem.FindControl("chkHeader")
    If (dgItem.ItemType = ListItemType.Item Or dgItem.ItemType = ListItemType.AlternatingItem) Then
        chkAllRows = dgItem.FindControl("chkItem")
        If (chkSelHeader.Checked) Then
            Response.Write("checked<br>")
            chkAllRows.Checked = True
        Else
            Response.Write("unchecked<br>")
            chkAllRows.Checked = False
        End If
    End If
Next


then when the CheckBox in the Header is checked, all the CheckBoxes get checked & assuming that the DataGrid has 10 rows, the text checked appears 10 items but when I uncheck the CheckBox in the Header so that all the other CheckBoxes get unchecked, then the CheckBox in the header gets unchecked but all the other CheckBoxes still remain checked & the page still displays the text checked (& not the text unchecked) 10 times!

What's causing this eccentric behavior?

Moreover, the On Error Resume Next is a must else ASP.NET generates the following error:

Object reference not set to an instance of an object.

pointing to the following If condition:

If (chkSelHeader.Checked) Then

Can someone please tell me what am I doing wrong? This is driving me nuts!!

Thanks

RON
*********
If you have an apple & I have an apple & we exchange our apples, then each of us will still have only 1 apple but if you have an idea & I have an idea & we exchange our ideas, then each of us will have 2 ideas
0
RN5A
12/4/2006 12:35:41 PM
Sub CheckAllRows(ByVal obj As Object, ByVal ea As EventArgs)
    Dim chkAllRows As CheckBox
    Dim chkSelHeader As CheckBox
    Dim dgItem As DataGridItem
    Dim bSelectAll as boolean = false

    For Each dgItem In dg1.Items
        If (dgItem.ItemType = ListItemType.Header) Then
            chkSelHeader = dgItem.FindControl("chkHeader")
            If (Not chkSelHeader IS Nothing) Then
                bSelectAll = chkSelHeader.checked
            End If
        Else If (dgItem.ItemType = ListItemType.Item Or dgItem.ItemType = ListItemType.AlternatingItem) Then
            chkAllRows = dgItem.FindControl("chkItem")
            If (Not chkAllRows Is Nothing) Then
                chkAllRows.Checked = bSelectAll
            End If
        End If
    Next
End Sub
 
Intelligence is a burden.
Jagdip Singh Ajimal
Manchester (and yes, I am a Manchester United fan)
0
jagdipa
12/4/2006 12:37:42 PM
I am sorry to say that you are wrong Jagdipa. Did you try out your code before posting?   

Only items bound to the data source are contained in the DataGrid's Items collection. Header, Footer & Separator are not included in this collection. This is the reason why

For Each dgItem In dg1.Items
    If (dgItem.ItemType = ListItemType.Header)
        chkSelHeader = dgItem.FindControl("chkHeader")


(where dgItem is of type DataGridItem) failed to find the CheckBox named chkHeader in the HeaderTemplate of the DataGrid. chkHeader can be found using

chkSelHeader = dg1.Controls(0).Controls(0).FindControl("chkHeader")

This is the entire code:
Sub CheckAllRows(ByVal obj As Object, ByVal ea As EventArgs)
    Dim dgItem As DataGridItem
    Dim chkAllRows As CheckBox
    Dim chkSelHeader As CheckBox
		
    chkSelHeader = dg1.Controls(0).Controls(0).FindControl("chkHeader")
		
    For Each dgItem In dg1.Items
        If (dgItem.ItemType = ListItemType.Item Or dgItem.ItemType = ListItemType.AlternatingItem) Then
            chkAllRows = dgItem.FindControl("chkItem")
            If (chkSelHeader.Checked) Then
                  chkAllRows.Checked = True
            Else
                  chkAllRows.Checked = False
            End If
        End If
    Next
End Sub

Thanks

RON
*********
If you have an apple & I have an apple & we exchange our apples, then each of us will still have only 1 apple but if you have an idea & I have an idea & we exchange our ideas, then each of us will have 2 ideas
0
RN5A
12/8/2006 9:04:07 PM

This might not be your exact answer but it will help you in doing client side. http://www.dotnetfunda.com/articles/article85.aspx


--
Thanks with regards,
Sheo Narayan
http://www.dotnetfunda.com/profile/SheoNarayan.aspx

Please "Mark as Answer", if this helped.
0
SheoNarayan
7/15/2008 8:40:22 PM

Hi

try this example:

<script type="text/javascript">

    function SelectAll(id) {

        var frm = document.forms[0];

        for (i=0;i<frm.elements.length;i++) {

            if (frm.elements[i].type == "checkbox") {

                frm.elements[i].checked = document.getElementById(id).checked;

            }

        }

    } 

</script>

<!-- assuming that SqlDataSource1 is the datasource for my GridView -->

<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" Width="400px">

    <Columns>

        <asp:TemplateField>

            <AlternatingItemTemplate>

                <asp:CheckBox ID="CheckBox1" runat="server" />

            </AlternatingItemTemplate>

            <ItemTemplate>

                <asp:CheckBox ID="CheckBox1" runat="server" />

            </ItemTemplate>

            <HeaderTemplate>

                <asp:CheckBox ID="cbSelectAll" runat="server" Text="Select All" />

            </HeaderTemplate>

            <HeaderStyle HorizontalAlign="Left" />

            <ItemStyle HorizontalAlign="Left" />

        </asp:TemplateField>

    </Columns>

</asp:GridView>

protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
 {

    if (e.Row.RowType == DataControlRowType.Header)
 {

        //adding an attribute for onclick event on the check box in the header

        //and passing the ClientID of the Select All checkbox

        ((CheckBox)e.Row.FindControl("cbSelectAll")).Attributes.Add("onclick", "javascript:SelectAll('" + ((CheckBox)e.Row.FindControl("cbSelectAll")).ClientID + "')");

    }

}

and to get checked row for delete

foreach (GridViewRow row in GridView1.Rows)
        {
            CheckBox checkbox = (CheckBox)row.FindControl("cbxId");

            if (checkbox.Checked == true)
            {
                int Id = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);
                your delete method

            }

        }

or check this post

http://forums.asp.net/t/1289995.aspx
       

Good Luck

 

0
yasserzaid
7/16/2008 1:47:41 PM

Wow!  was this post really started on 12-04-2006 or is it just me??


If this answered your query please "Mark as Answer"
0
Nilesh
7/16/2008 2:46:52 PM
Reply:

Similar Artilces:

checking checkbox is checked or not using checkbox.checked
Hi,my checkbox is<asp:CheckBox ID="Chkcity" runat="server" Text="My own city"  OnCheckedChanged="EventHandler"/>code behind: Private Sub Chkcity_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Chkcity.CheckedChangedif (Chkcity ...............)end if End SubERROR    'EventHandler' is not a member of 'ASP.bpoaddjob_aspx'.    Please Mark the post as "ANSWER" if it helps you I think it should be like this:<asp:CheckBox ID="Chkcity"...

Check for at least one checkbox checked
I have 13 checkboxes in a cell on my form. OnSubmit I need to make sure at least one of those checkboxes is checked. How can I do that with JavaScript? Try a custom validator and get the check boxes by dropping either all of the necessary client ids or the base id with the number of boxes (if using a checkboxlist). function IsThereAnyChecked() { var num = document.Form1.elements.length; var i; var bAnyChecked = false; for (var i=0; i<num; i++) { if (document.Form1.elements[i].type == 'checkbox') { if (document.Form1.elements[i].checked==true) ...

A checkbox that checks the other checkboxes...
Hi everyone, I'd like to create a checkbox that checks all the checkboxes that are contained in my repeater. Does anyone know how to do this ??? I've tried some javascripts found on the net but nothing works... :'( Please help me ! It's rather urgent ! Thanks for answering ! ^^ Hello... I don't know how to make the page react when you check the box (actually I'm having trouble doing so with a dropdownlist, so if you have any idea :p) but if you add a button that you click after checking the box, you can add in the code behind file [ CheckBox1.Checked = true ] and do so to all t...

Check All Check Box While Check Header CheckBox
 hello...I have two grid on same page...both grid contains header checkbox and item checkbox i want that if use check header checkbox then all item check box checked,i have javascript for this functinality but problem is that when i click on header check box of first grid then checkbox of second grid also checked that i dnt want i want to perform this operation on one grid at one time.i have attache my script also...plz help me....thanks<script type="text/javascript">        function SelectAll(ID)      &nbs...

not getting checkbox value from checked checkbox in repeater
hi all,   i have the following method that is being called when i save some info using a button click event:   private int SearchForCheckboxCheckedInPreviousAppraiserNotes() { int assocNoteID = -1; foreach (RepeaterItem item in PreviousAppraiserNotes.Items) { CheckBox cbAssociateToNoteID = (CheckBox)item.FindControl("cbAssociateToNoteID"); if (cbAssociateToNoteID.Checked) { assocNoteID = Convert.ToInt32(cbAssociateToNoteID.Attributes["noteID&quo...

Getting Error While Checking Whether CheckBox Is Checked Or Not
Hello Friends, I am getting following problem  I am using VS 2003. And VB.Net Error Message   Exception Details: System.NullReferenceException: Object reference not set to an instance of an object. Source Error:  Line 227:            ObjCheck = CType(Me.FindControl("Customer" + I.ToString()), CheckBox)Line 228:            ObjText = CType(Me.FindControl("CustomerCode" + I.ToString()), TextBox)Line 229:  &...

How do I set a checkbox to checked when another checkbox in a DG row is checked?
I have a datagrid with rows of labels, textboxes, and checkboxes.  These rows show information about customers.  When a user checks one of the checkboxes, I need the other textbox to become checked as well.  When the user unchecks the checkbox, nothing should happen.  See code below.  Any ideas?  The trick is finding the checkbox control for that specific row.  Thanks!!!! <asp:GridView ID="CustomFieldsGridView" width="100%" runat="server" AutoGenerateColumns="False" DataKeyNames="CustomizableFieldCode" DataSourceID="CustomFieldsObjectDataSource" ShowHe...

how to check all the row level checkbox when header level checkbox is checked
hello i m working on one site which requires the functionality like yahoo, that is when we check header level check box then all row level checkbox is checked.i m sending my code here....<script language="javascript" type="text/javascript">        function Check(chk)        {          alert("abc");            if(document.form1.HeaderLevelCheckBox.checked==true)    ...

detecting the checking of atleast one checkbox in a bunch of checkboxes in a page
Hello All. I want one help. I have a bunch of checkboxes in a page. Of them atleast one (max any number) should be checked. Is there a way to detect (except check the checkboxes individually) if atleast one has been checked? this should be done in code-behind. i know that i would be able to do it by checking the individual boxes checked condition. Is there any other way out? Thanks,Praveen Raju Have you looked at validation controls?  There's a tutorial on this site that may help you with them. JeffPlease: Don't forget to click "Mark as Answer" on the post that help...

How to Check if Checkboxes are Checked? ^_~
Hullo,What I'm basically trying to do is see if a checkbox is checked, and if it is, then change the value of a hiddenfield to update a database.  Here's my code:  protected void Rankbox_CheckedChanged(object sender, EventArgs e) { if (Rankbox = checked) { Rank.Value = 1; } else if (Rankbox = unchecked) { Rank.Value = 0; } } My checkbox is named "Rankbox", and the hidden field with information that needs changing is "Rank".  The error Visual Studio is giving me basically says that it hates the if sta...

Check to see if Checkbox is checked
  Hello All, Currently my application allows user to select the days which they worked and the days are presented in the form of checkboxes which means there are 7 checkboxes for Monday to Sunday. The problem is: I want my users to at least check one box: How do I write the code in VB.NET to ensure that at least one box is checked? I have no totally no idea at all.  Any experts care to shed some light? Thanks!Sincerely Yours, Abupapa hi,Pls go through the link below: This is a very good article.. i think this will meet your requirement.http://codeclimber.net.nz/archive/2007/0...

How to check if CheckBox is check in C#
Hi all,Please help.I have  a gridview and inside the <HeaderTemplate> I declare a checkBox as follow: <HeaderTemplate > <asp:Label ID="Label6" runat="server" Text='Code' CssClass="dirStyle1"></asp:Label>&nbsp; <asp:CheckBox ID="CheckBox1" runat="server"/> </HeaderTemplate>so let say i have a button for PostBack/Submit so how do I check if the checkbox is check?I tried ------------------------------------------------------------ CheckBox chbx = GridView1.FindControl("CheckBox1&qu...

gridview check if checkbox is checked
 I have a column with checkboxes in my gridview, I want to check each row if the checkbox was checked, if yes do something with the data of that row. How do I do that?I added the checkboxes the following way <asp:TemplateField>                                <ItemTemplate>                         &nb...

Getting checkbox check to work in order to hide GridView columns if or if not checked
Ok, I have a checkbox outside my gridview on my aspx page.  I want to check whether it's checked or not and if it is not checked, hide 2 columns.  If it is checked, show the 2 columns.  So far, it works if I put in just this, and no check on the checkbox.  This hides my 2 columns:     Protected Sub SearchResults_RowDataBound(ByVal s As Object, ByVal e As GridViewRowEventArgs)         If e.Row.RowType = DataControlRowType.DataRow Then              &nb...

if checkbox is checked , then all the checkboxlist should be checked
i have a checkbox list and a checkbox , i want f the checkbox is checked then all the checkboxes in the checkboxlist should be checked as well.   Please suggest , if there is any way out   Thanksneelu gupta Do u want this to be done on the client side or server side? And are these check boxes server controls or html controls??Shravan Addaypally MCP maybe this thread can help.> penny for a thought...

Validation to Check if checkbox is checked
Hi,Which Validation statement should i use to check whether a checkbox is checked?Thanks You can also use CustomValidator for validate if check box is checked or not. Here is the example:   <script> function checkTemp() {             if (document.getElementById("valcheckBoxTemp").checked)                         args.IsValid = true;             else ...

How to check checkbox is checked or not dynamically....
Hai friends.... I am creating checkbox dynamically............ dim check(100) as checkbox dim cell as new tablecell check(i)=new checkbox() is there any short method to check whether non of the checkbox is checked........... Ambrose... Help me......Winners Never QuitQuitters Never Win You could do this to check if check boxes are checked If CheckBox1.Checked Then    Message.Text &= "CheckBox 1 was checked<br/>"  End If  If CheckBox2.Checked Then    Message.Text &= "CheckBox 2 was checked<br/>"  End ...

leaving the checkbox checked after it is checked
not by default that is. I apologize for double posting, I've been warned that my subject was too vague. Hello everyone, I hope someone can help me with this problem. Here is what I am trying to do: - Job request is entered in Form-A. - When Form-A is submitted, apple.cgi tells the user the form is successfully submitted and at the same time appends the request into an html file (banana.html) that can be seen on the web. - There is a checkbox near each request on Form-A. I want that when the checkbox is checked (meaning the job is done), the job request disappears f...

how to check if checkboxes in datalist is checked?
hi, i have a checkbox in datalist itemtemplate. i need to have a validation that checks if theres atleast 1 checkbox in datalist item that is checked, when button delete is click. Thanks   Here is code to read value of checkbox in datalist control. foreach (DataListItem item in this.dataListName.Items) { //if check box is an html control HtmlInputCheckBox chk = item.Cells[0].FindControl("checkBoxName") as HtmlInputCheckBox; //OR if checkbox is server side asp.net control CheckBox chk = item.Cells[0]....

how to check the checkbox checked property
hi guyz i have a server side chkbox control and on the basis of it i want to enable/disable a textbox at client side, i had registered an event in my .cs class, but using java script im unable to chkeck whether the checkBox is checked or not (at client side) im doing it on  .acx control and i donot have a form object on it. i tried alot but unable to find the solution kindly tell me if any1 knows..........     thnx For a CheckBox this is all that you need. If a CheckBoxList there is a little more involved. /////////////////////////////////// aspx file///////...

How to get changed CheckBox.Checked value from dynamically created CheckBox inside EditItemTemplate in ListView
 I have a problem in getting CheckBox.Checked value from CheckBox controls which are dynamically created into EditItemTemplate in ListView.To create the Checkbox Controls in EditItemTemplate, I added PlaceHolder control there and spreaded CheckBox controls there in ItemDataBound event handler which need to be created. This works. But how can I get the changed checkbox value from these Controls? I tried to attach the CheckedChanged event to CheckBox controls to get the values in CheckedChanged event and save to Session to pull out on next PostBack, but This event doesn't fire...

javascript: check all check box in a perticular row , when i check a checkbox i that perticuler row
Hi Friends,I have a gridview. and I am having checkboxes in all the columns and all the rows. Like it is about selecting subjects.My Problem is when I select a Checkbox in First column of any row, all the checkboxes in that particular row should also be selected.How can I do this... . I have done all checkboxes checked for column, but no idea about row.Please guide.Thanks. Hi, this can be done with the help of jQuery, a great & free javascript library. Take a look at this article: Check All Checkboxes in GridView using JQuery. Grz, Kris.Read my blog. Handy Firefox plugins for web dev...

Error in JavaScript To Check All CheckBox In only in ONe DataGrid When Having More than one DataGrid in One Page
Hello Guys, I am having total 8 DataGrid on a Page. I want to apply javascript so that if i click on CheckBox in Header Row Then All CheckBox inside ItemTemplate should be Checked automatically. I applied the following javascript to do so: function CheckAll( checkAllBox ) { var frm = document.form1; var ChkState=checkAllBox.checked; for(i=0;i { e=frm.elements[i]; if(e.type=='checkbox' && e.name.indexOf('chkView') != -1) ...

checkbox does not get checked..
I have a group of checkboxes. In property checkbox1 I set the checked property to true.When I run the program I have a reset button to check this checkbox1.  In the reset button I set checkbox1.checked = true.  I debugged and saw the program passed this line but the checkbox1 was not checked.  Instead, the checkbox was still checked with others one.  How do I check it? thank you   You should set AutoPostBack to TRUE in your CheckBox Regards,Vinz"Code, Beer and Music" that's my way of being a programmer!How to get your Forum Question Ans...

Web resources about - Check One CheckBox To Check All CheckBoxes - asp.net.getting-started

Quick Tip Friday: Create Checklists Faster with Auto-Checkboxes
/ We know a lot of Evernote users love checkboxes for to-dos, grocery lists, and more. Creating checkboxes in Evernote is easy: you can add them ...

Group sues Michigan secretary of state over citizenship checkboxes for voters
... rights coalition filed a federal lawsuit today in Detroit challenging Secretary of State Ruth Johnson’s decision to have U.S. citizenship checkboxes ...

Evernote for BlackBerry 10 updated with checkboxes, image and audio attachments
Evernote has updated its recently launched app for the BlackBerry 10 platform with new features, alongside speed improvements and two-step verification. ...

Add checkboxes to an Excel spreadsheet
Tgood37 asked the Answer Line forum how to add checkboxes to Excel spreadsheets, and how to make sure that checking a box will have an effect. ...

Solving Twitter and LinkedIn’s Ad Problem: It’s Time to Ditch the Checkboxes
Last week was a big one for social media giants Twitter and LinkedIn. They admitted to their investors and to the world that their display advertising ...

Simple trick for testing forms full of checkboxes with django
... testing style. What matters is that you have tests. Image via Wikipedia But what do you do when you want to test a form with a bunch of checkboxes? ...

Checkboxes that kill your product
Alexander Limi / Alex Limi : Checkboxes that kill your product — (To read this article with its formatting and typography intact, click here) ...

Evernote for BlackBerry 10 updated with checkboxes, image and audio attachments
... 10 platform with new features, alongside speed improvements and two-step verification. Among the new features is the ability to insert checkboxes ...

Bento for iPad for iPad on the iTunes App Store
Read reviews, get customer ratings, see screenshots, and learn more about Bento for iPad on the App Store. Download Bento for iPad and enjoy ...

Facebook Users in Brazil and India Can Syndicate Their Profiles to Orkut
Facebook users in Brazil and India can now connect their profiles with their account on Orkut , Google’s existing social network. Those who link ...

Resources last updated: 2/14/2016 7:26:46 PM