Click here to Skip to main content
15,901,505 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have the gridview with checkboxes (Select All and Single Select). When I select select all option, it's getting fired and updating.

When i delete(uncheck) the last items, it will not fire and not values not updating. This problem coming only when i uncheck the last items in the check box...

What is the problem...?

see my code
------------
JavaScript
<script type="text/javascript" language="javascript">
     //Reference of the GridView. 
     var TargetBaseControl = null;
     //Total no of checkboxes in a particular column inside the GridView.
     var CheckBoxes;
     //Total no of checked checkboxes in a particular column inside the GridView.
     var CheckedCheckBoxes;
     //Array of selected item's Ids.
     var SelectedItems;
     //Hidden field that wil contain string of selected item's Ids separated by '|'.
     var SelectedValues;
     window.onload = function () {
         //Get reference of the GridView. 
         try {
             TargetBaseControl = document.getElementById('<%= GridView1.ClientID %>');
         }
         catch (err) {
             TargetBaseControl = null;
         }
         //Get total no of checkboxes in a particular column inside the GridView.
         try {
             CheckBoxes = parseInt('<%= GridView1.Rows.Count %>');
         }
         catch (err) {
             CheckBoxes = 0;
         }
         //Get total no of checked checkboxes in a particular column inside the GridView.
         CheckedCheckBoxes = 0;
         //Get hidden field that wil contain string of selected item's Ids separated by '|'.
         SelectedValues = document.getElementById('<%= hdnFldSelectedValues.ClientID %>');
         //Get an array of selected item's Ids.
         if (SelectedValues.value == '')
             SelectedItems = new Array();
         else
             SelectedItems = SelectedValues.value.split('|');
         //Restore selected CheckBoxes' states.
         if (TargetBaseControl != null)
             RestoreState();
     }
     function HeaderClick(CheckBox) {
         //Get all the control of the type INPUT in the base control.
         var Inputs = TargetBaseControl.getElementsByTagName('input');
         //Checked/Unchecked all the checkBoxes in side the GridView & modify selected items array.
         for (var n = 0; n < Inputs.length; ++n)
             if (Inputs[n].type == 'checkbox' && Inputs[n].id.indexOf('chkBxSelect', 0) >= 0) {
                 Inputs[n].checked = CheckBox.checked;
                 if (CheckBox.checked)
                     SelectedItems.push(document.getElementById(Inputs[n].id.replace('chkBxSelect', 'hdnFldId')).value);
                 else
                     DeleteItem(document.getElementById(Inputs[n].id.replace('chkBxSelect', 'hdnFldId')).value);
             }
         //Update Selected Values. 
         SelectedValues.value = SelectedItems.join('|');
         //Reset Counter
         CheckedCheckBoxes = CheckBox.checked ? CheckBoxes : 0;
     }
     function ChildClick(CheckBox, HCheckBox, Id) {
         //Modifiy Counter;            
         if (CheckBox.checked && CheckedCheckBoxes < CheckBoxes)
             CheckedCheckBoxes++;
         else if (CheckedCheckBoxes >= 0)
             CheckedCheckBoxes--;
         //Change state of the header CheckBox.
         if (CheckedCheckBoxes < CheckBoxes)
             HCheckBox.checked = false;
         else if (CheckedCheckBoxes == CheckBoxes)
             HCheckBox.checked = true;
         //Modify selected items array.
         if (CheckBox.checked)
             SelectedItems.push(Id);
         else
             DeleteItem(Id);
         //Update Selected Values. 
         SelectedValues.value = SelectedItems.join('|');
     }
     function RestoreState() {
         //Get all the control of the type INPUT in the base control.
         var Inputs = TargetBaseControl.getElementsByTagName('input');
         //Header CheckBox
         var HCheckBox = null;
         //Restore previous state of the all checkBoxes in side the GridView.
         for (var n = 0; n < Inputs.length; ++n)
             if (Inputs[n].type == 'checkbox' && Inputs[n].id.indexOf('chkBxSelect', 0) >= 0)
                 if (IsItemExists(document.getElementById(Inputs[n].id.replace('chkBxSelect', 'hdnFldId')).value) > -1) {
                     Inputs[n].checked = true;
                     CheckedCheckBoxes++;
                 }
                 else
                     Inputs[n].checked = false;
             else if (Inputs[n].type == 'checkbox' && Inputs[n].id.indexOf('chkBxHeader', 0) >= 0)
                 HCheckBox = Inputs[n];
             //Change state of the header CheckBox.
         if (CheckedCheckBoxes == 0)
                 CheckedCheckBoxes = null;
         else if (CheckedCheckBoxes < CheckBoxes)
            
             HCheckBox.checked = false;
         else if (HCheckBox == null)
             HCheckBox = null;
         else if (CheckedCheckBoxes == CheckBoxes)
             HCheckBox.checked = true;
     }
     function DeleteItem(Text) {
         var n = IsItemExists(Text);
         if (n > -1)
             SelectedItems.splice(n, 1);
     }
     function IsItemExists(Text) {
         for (var n = 0; n < SelectedItems.length; ++n)
             if (SelectedItems[n] == Text)
                 return n;
         return -1;
     }
     function ItemMouseOver(oRow, chkBxMail) {
         oCheckBox = document.getElementById(chkBxMail);
         //oImage = document.getElementById(imgMail);
         if (!oCheckBox.checked) {
             oCheckBox.style.display = '';
             //oImage.style.display = 'none';
             oRow.originalBackgroundColor = oRow.style.backgroundColor
             oRow.style.backgroundColor = '#EAEAEA';
         }
         if (oCheckBox.checked) {
             oCheckBox.style.display = '';
             //oImage.style.display = 'none';
             oRow.originalBackgroundColor = oRow.style.backgroundColor
             oRow.style.backgroundColor = 'lightyellow';
         }
     }
     function ItemMouseOut(oRow, chkBxMail) {
         oCheckBox = document.getElementById(chkBxMail);
         //oImage = document.getElementById(imgMail);
         if (!oCheckBox.checked) {
             oCheckBox.style.display = 'none';
             //oImage.style.display = '';
             oRow.style.backgroundColor = oRow.originalBackgroundColor;
             oRow.style.backgroundColor = '#EAEAEA';
         }
         if (oCheckBox.checked) {
             oCheckBox.style.display = 'none';
             //oImage.style.display = '';
             oRow.style.backgroundColor = oRow.originalBackgroundColor;
             oRow.style.backgroundColor = 'lightyellow';
         }
     }
   
  </script>

ASPX Code
---------
<asp:GridView ID="GridView1" runat="server" align="center" AllowPaging="true" DataKeyNames="PrNo,RevisionNo"
                                 AutoGenerateColumns="False" class="tabulardata" DataSourceID="SqlDataSource1" 
                                 HorizontalAlign="Center" Width="100%" OnRowCommand="GridView1_RowCommand" 
                                 OnRowDataBound="GridView1_RowDataBound" OnRowDeleted="GridView1_RowDeleted" OnRowDeleting="GridView1_RowDeleting">
                                 <columns>
                                     <asp:TemplateField HeaderText="Select">
                                            <itemtemplate>
                                                <asp:CheckBox ID="chkBxSelect" type="checkbox" runat="server" OnCheckedChanged="chkSelect_CheckedChanged" AutoPostBack="true"/>
                                                <asp:HiddenField ID="hdnFldId" runat="server" Value='<%# Container.DataItemIndex + 1%>' />
                                                 <asp:Label ID="lblActive" runat="server" Text='<%# Eval("IsActive") %>'> 
                                            </itemtemplate>
                                            <HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="50px" />
                                            <itemstyle horizontalalign="Center" verticalalign="Middle" width="50px" />
                                            <HeaderTemplate>
                                                <asp:CheckBox ID="chkBxHeader" onclick="javascript:HeaderClick(this);"  OnCheckedChanged="chkSelectAll_CheckedChanged" runat="server" AutoPostBack="true"/>
                                            </HeaderTemplate>
                                     
                                     <asp:TemplateField HeaderText="Sl.No" ItemStyle-HorizontalAlign="Center" 
                                         ItemStyle-Width="4%">
                                         <itemtemplate>
                                           <%# Container.DataItemIndex + 1%>
                                         </itemtemplate>
                                      
                                     <asp:BoundField HeaderText="No." Visible="true" DataField="No"
                                         ItemStyle-HorizontalAlign="center" ReadOnly="true" SortExpression="No">
                                         <itemstyle horizontalalign="Center" width="40%" />
                                     
                                     <asp:TemplateField HeaderText="No" Visible="false" HeaderStyle-HorizontalAlign="Center" ItemStyle-Width="10%"> 
                                        <itemtemplate> 
                                            <asp:Label ID="lblNo" runat="server" Text='<%# Eval("No") %>'>
                                        </itemtemplate> 
                                         <HeaderStyle HorizontalAlign="Center" />
                                    
                                   
                                      <asp:BoundField HeaderText="RevisionNo" Visible="true" DataField="RevisionNo"
                                         ItemStyle-HorizontalAlign="center" ReadOnly="true" SortExpression="RevisionNo">
                                         <itemstyle horizontalalign="Center" width="2%" />
                                     
                                     <asp:TemplateField HeaderText="RevNo" Visible="false" HeaderStyle-HorizontalAlign="Center" > 
                                        <itemtemplate> 
                                            <asp:Label ID="lblReNo" runat="server" Text='<%# Eval("ReNo") %>'>
                                        </itemtemplate> 
                                         <HeaderStyle HorizontalAlign="Center" />
                                     
                                      <asp:BoundField HeaderText="RevisionHistory" Visible="true" DataField="RevisionHistory"
                                         ItemStyle-HorizontalAlign="center" ReadOnly="true" SortExpression="RevisionHistory">
                                         <itemstyle horizontalalign="Center" width="40%" wrap="true" />
                                     
                                     <asp:TemplateField HeaderText="Edit" ItemStyle-HorizontalAlign="Center">
                                         <itemtemplate>
                                             <asp:HyperLink ID="hyperlink1"  onclick="" BorderStyle="None" runat="server"  
                                                 ImageUrl="~/images/Edit.png" 
                                                 Width="50%" >
                                         </itemtemplate>
                                         <itemstyle horizontalalign="Center" width="6%" />
                                     
                                     <asp:TemplateField HeaderText="Delete" ItemStyle-HorizontalAlign="Center">
                                         <itemtemplate>
                                             <asp:ImageButton ID="btnDelete" runat="server" CommandName="Delete" Height="20" 
                                                 ImageUrl="~/images/DeleteImage.png" OnClientClick="return confirm('Are you sure you want to delete this PR Number.?');"
                                                 CommandArgument='<%# container.DisplayIndex%>' 
                                                  Width="20" />
                                         </itemtemplate>
                                         <itemstyle horizontalalign="Center" width="2%" />
                                     
                                 </columns>
                                  <emptydatarowstyle backcolor="LightBlue" forecolor="Red" />
                                   <emptydatatemplate>
                                      <asp:image id="NoDataImage" imageurl="~/Images/Edit.png" alternatetext="No Image" runat="server"/>
                                            No Data Found.  
                                   </emptydatatemplate> 
                             
                              <asp:HiddenField ID="hdnFldSelectedValues" runat="server" />

ASPX VB Code
------------


[EDIT] Cut code from comment by author and pasted here instead. -- Slacker007

VB
see my ASPX Code
----------------
 Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        txtPRDate.Attributes.Add("readonly", "readonly")
        txtReceivedDt.Attributes.Add("readonly", "readonly")
        If Not IsPostBack Then
         
            'Fill Grid
            BindGridView()
         
            If Request("Page") <> "" Then
                GridView1.PageIndex = Request("Page") - 1
            End If
        End If
    End Sub
 Private Sub BindGridView()
        GridView1.DataBind()
    End Sub
 Protected Sub GridView1_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles GridView1.PageIndexChanging
        GridView1.PageIndex = e.NewPageIndex
        BindGridView()
    End Sub
 Protected Sub chkSelectAll_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs)
        Dim chkAll As CheckBox = DirectCast(GridView1.HeaderRow.FindControl("chkBxHeader"), CheckBox)
        Conn.Open()
        If chkAll.Checked = True Then
            For Each gvRow As GridViewRow In GridView1.Rows
               
                chkSel.Checked = True
                Qry = ""
                Qry = "update statement"
                Cmd.Connection = Conn
                Cmd.CommandText = Qry
                Cmd.ExecuteNonQuery()
                BindGridView()
            Next
        Else
            For Each gvRow As GridViewRow In GridView1.Rows
               
                chkSel.Checked = False
                Qry = ""
                Qry = "update statement"
                Cmd.Connection = Conn
                Cmd.CommandText = Qry
                Cmd.ExecuteNonQuery()
                BindGridView()
            Next
        End If
        Conn.Close()
    End Sub
    Protected Sub chkSelect_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs)
       
        Conn.Open()
        ' Dim txtMHrs As TextBox = DirectCast(grdRow.FindControl("txtManHours"), TextBox)
        For Each gvRow As GridViewRow In GridView1.Rows
           
            If chkSel.Checked = True Then
                Qry = ""
                Qry = "update statement"
                Cmd.Connection = Conn
                Cmd.CommandText = Qry
                Cmd.ExecuteNonQuery()
                BindGridView()
            Else
                Qry = ""
                Qry = "update statement"
                Cmd.Connection = Conn
                Cmd.CommandText = Qry
                Cmd.ExecuteNonQuery()
                BindGridView()
            End If
        Next
        Conn.Close()
    End Sub
    Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand
        Try
            If e.CommandName = "Delete" Then
               
                'Delete the record 
                If PrNo.ToString IsNot Nothing Then
                    SqlDataSource1.DeleteCommand = "delete stmt"
                    SqlDataSource1.DataBind()
                End If
            End If
        Catch ex As Exception
            WriteLogFile(Me.[GetType]().Name, "GridView1_RowCommand()", ex.Message.ToString())
        End Try
    End Sub
    Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
        
        If e.Row.RowType = DataControlRowType.DataRow AndAlso (e.Row.RowState = DataControlRowState.Normal OrElse e.Row.RowState = DataControlRowState.Alternate) Then
            Dim chkBxSelect As CheckBox = DirectCast(e.Row.Cells(0).FindControl("chkBxSelect"), CheckBox)
            Dim chkBxHeader As CheckBox = DirectCast(Me.GridView1.HeaderRow.FindControl("chkBxHeader"), CheckBox)
            Dim hdnFldId As HiddenField = DirectCast(e.Row.Cells(0).FindControl("hdnFldId"), HiddenField)
            Dim chkBxMail As CheckBox = DirectCast(e.Row.Cells(0).FindControl("chkBxSelect
Posted
Updated 4-Aug-11 23:57pm
v7
Comments
Herman<T>.Instance 5-Aug-11 4:21am    
please show aspx code
gani7787 5-Aug-11 4:29am    
Removed very large code block from comment and put in your original question...at the end. -- Slacker007
Herman<T>.Instance 5-Aug-11 4:41am    
this is VB.NET code not aspx --> <asp:GridView runat="server".....
walterhevedeich 5-Aug-11 4:49am    
User Improve question and post your code on the question. Do not post it as a comment as it is harder to read.
Herman<T>.Instance 5-Aug-11 6:09am    
1: When I look at your method I see that despite the fact you choose select all or select current row you go passed all rows.

In the select row case you only want to update that row I presume.
So first find your GridViewRow in which the checbox was clicked.

<pre>CheckBox checkbox = sender as CheckBox
GridViewRow row = checkbox.NamingContainer as GridViewRow</pre>

2: Have you set a breakpoint in the first line in the chkSelect_CheckedChanged method to see if it really doesn't fire?

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900