Will a checked GridView Header CheckBox affect other checkboxes in other pages of the Gridview?

Donald Symmons 3,066 Reputation points
2024-01-03T04:06:32.6933333+00:00

I want to know if I have a checkbox in a Gridview head that checks all checkboxes in the gridview row and the Gridview has paging, will the check All checkbox check all the row checkboxes in the Gridview regardless of the which page the checkbox is?

What I mean is, I have a checkbox in the head of my Gridview, called "checkAll" and my Gridview has pagnation. I also have a button outside of the gridview. So, In the Gridview are records with email addresses in the grid row such that when I check the checboxes and click button, an email is sent to the records in the rows that are checked.

I have a JavaScript that makes the checkAll checkbox check all checkboxes that are visible on the screen. But there are other pages in the Gridview, so will it also check the other checkboxes in other pages, so that when the email is sent the email records that are also on other pages can receive the email as well?

<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
        <div class="col-sm-11" style="width: 100%; margin: 0 auto; padding: 10px; margin-right: auto; margin-left: auto;">
            <asp:Label ID="createby" runat="server" Text="4"></asp:Label>
            <asp:UpdatePanel ID="panel" runat="server" ChildrenAsTriggers="true">
                <ContentTemplate>
                    <div class="container-fluid p-3 mb5 bg-white rounded" id="card" style="margin: 0 auto; padding: 10px; border: 1.3px solid #e4e7e8;">
                        <asp:GridView ID="GridView1" runat="server" GridLines="None" DataKeyNames="Id" AllowPaging="true" HeaderStyle-BackColor="#fdfdfd" HeaderStyle-Font-Bold="false" HeaderStyle-ForeColor="#05214d" HeaderStyle-Font-Size="10pt" Font-Size="9pt"
                            AutoGenerateColumns="false" HeaderStyle-HorizontalAlign="left" RowStyle-HorizontalAlign="Left" OnPageIndexChanging="OnPageIndexChanging" class="table" Width="100%">
                            <EmptyDataTemplate>
                                <div style="text-align: center; font-weight: 500; margin-top: 2%;">
                                    <i class="fal fa-file-times" style="margin: 0 auto; font-size: 30pt; color: #145c7c;"></i>
                                    <p id="P1" runat="server" style="font-size: 11pt; font-weight: 400;">No Recipient</p>
                                </div>
                            </EmptyDataTemplate>
                            <Columns>
                                <asp:TemplateField>
									<HeaderTemplate>                                                         			  	<asp:CheckBox ID="checkkAll" runat="server" onclick="SelectAll(this)" />                                                     				      </HeaderTemplate>
                                    <ItemTemplate>
                                        <asp:CheckBox ID="CheckSelected" runat="server" />
                                    </ItemTemplate>
                                </asp:TemplateField>
                                <asp:BoundField DataField="Id" HeaderText="ID" HeaderStyle-Font-Bold="false" />
                                <asp:BoundField DataField="Recipient" HeaderText="Recipients" HeaderStyle-Font-Bold="false" />

                                <asp:TemplateField HeaderText="Email" HeaderStyle-Font-Bold="false">
                                    <ItemTemplate>
                                        <asp:HyperLink ID="emailLink" runat="server" Text='<%# Eval("RecEmail") %>' NavigateUrl='<%# Eval("RecEmail", "mailto:{0}") %>' />
                                    </ItemTemplate>
                                </asp:TemplateField>
                                <asp:TemplateField>
                                    <ItemTemplate>
                                        <asp:HiddenField ID="hfSeq" Value='<%# Eval("DocumentData") != System.DBNull.Value ? Convert.ToBase64String((byte[])Eval("DocumentData")) : string.Empty %>' runat="server" />
                                      
                                    </ItemTemplate>
                                </asp:TemplateField>

                                <asp:BoundField DataField="AwardDate" HeaderText="Date" HeaderStyle-Font-Bold="false" />

                            </Columns>
                        </asp:GridView>

                        <div style="float: right; font-size: 10pt; margin-right: 1%;">
                            Showing&nbsp;Page&nbsp;
        <asp:Label ID="lblPageIndex" runat="server" Text="Label" />
                            &nbsp;of&nbsp;
        <asp:Label ID="lblTotalPage" runat="server" />
                            (<asp:Label ID="lblTotal" runat="server" />
                            Records)&nbsp;&nbsp;
        <div class="dvPager">
            <asp:Repeater ID="rptPager" runat="server">
                <ItemTemplate>
                    <asp:LinkButton ID="lnkPage" runat="server" Text='<%#Eval("Text") %>' CommandArgument='<%# Eval("Value") %>'
                        CssClass='<%# Convert.ToBoolean(Eval("Enabled")) ? "page_enabled" : "page_disabled" %>'
                        OnClick="Page_Changed" OnClientClick='<%# !Convert.ToBoolean(Eval("Enabled")) ? "return false;" : "" %>'></asp:LinkButton>
                </ItemTemplate>
            </asp:Repeater>
        </div>
                        </div>
                        <br />
                        <br />
                    </div>
                </ContentTemplate>
            </asp:UpdatePanel>
        </div>
        <div class="col-sm-10" style="width: 100%; margin: 0 auto; padding: 10px; padding-bottom: 10px;">
            <div class="row">
                <div class="col-sm-11">
                    <div class="form-group">
                        <asp:Label CssClass="element" ID="Label1" runat="server">Subject</asp:Label>
                        <div class="input-group">
                            <asp:TextBox ID="TextSubject" runat="server" AutoCompleteType="None" Height="32" CssClass="form-control" placeholder="e.g Document File" />
                        </div>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-sm-11">
                    <div class="form-group">
                        <div class="input-group">
                            <asp:TextBox ID="txtBody" runat="server" CssClass="form-control" Width="100%" Font-Size="10pt" TextMode="MultiLine" placeholder="e.g. Please download your documents below" Style="overflow: hidden; resize: none;" oninput="Resize(this)" />
                            <script type="text/javascript">
                                function Resize(textbox) {
                                    textbox.style.height = "";
                                    textbox.style.height = Math.min(textbox.scrollHeight, 300) + "px";
                                }
                            </script>
                        </div>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-sm-11">
                    <div class="form-group">
                        <div class="input-group">
                            <asp:Button ID="SendBtn" CssClass="btn btn-primary" Text="Send Documents" runat="server" OnClick="SendBulkDocument" />
                        </div>
                    </div>
                </div>
            </div>
        </div>

JavaScript

 <script type="text/javascript">
        function SelectAll(headerCheckBox) {
            //Get the reference of GridView.
            var GridView = headerCheckBox.parentNode.parentNode.parentNode;

            //Loop through all GridView Rows except first row.
            for (var i = 1; i < GridView.rows.length; i++) {
                //Reference the CheckBox.
                var checkBox = GridView.rows[i].cells[0].getElementsByTagName("input")[0];

                //If CheckBox is checked, change background color the GridView Row.
                if (headerCheckBox.checked) {
                    checkBox.checked = true;
                    GridView.rows[i].className = "selected";
                } else {
                    checkBox.checked = false;
                    GridView.rows[i].className = "";
                }
            }
        }
    </script>
protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
                using (SqlConnection con = new SqlConnection(constr))
                {
                    using (SqlCommand cmd = new SqlCommand("SELECT * FROM DocumentTable"))
                    {
                        using (SqlDataAdapter sda = new SqlDataAdapter())
                        {

                            cmd.Connection = con;
                            sda.SelectCommand = cmd;
                            using (DataTable dt = new DataTable())
                            {
                                sda.Fill(dt);

                                GridView1.DataSource = dt;
                                GridView1.DataBind();
                            }
                        }
                    }
                }

            }
        }
        protected void SendBulkDocument(object sender, EventArgs e)
        {
            //Create a temporary DataTable
            DataTable dtCustomers = new DataTable();
            dtCustomers.Columns.AddRange(new DataColumn[3] { new DataColumn("Recipient", typeof(string)),
                        new DataColumn("RecEmail", typeof(string)),
                        new DataColumn("DocumentData",typeof(string)) });

            //Copy the Checked Rows to DataTable
            foreach (GridViewRow row in GridView1.Rows)
            {
                if ((row.FindControl("CheckSelected") as CheckBox).Checked)
                {
                    dtCustomers.Rows.Add(row.Cells[2].Text, (row.FindControl("emailLink") as HyperLink).Text, (row.FindControl("hfSeq") as HiddenField).Value);
                }
            }

            string subject = TextSubject.Text;
            string body = "Dear {0},<br /><br />" + txtBody.Text + "<br /><br />";
            for (int i = 0; i < dtCustomers.Rows.Count; i++)
            {
                SendEmail(dtCustomers.Rows[i]["Recipient"].ToString(),dtCustomers.Rows[i]["RecEmail"].ToString(), subject, string.Format(body, dtCustomers.Rows[i]["Recipient"]), Convert.FromBase64String(dtCustomers.Rows[i]["DocumentData"].ToString()));

            }

        }

        private bool SendEmail(string recipient,string recEmail, string subject, string body, byte[] attachments)
        {
            SmtpClient client = new SmtpClient();
            client.UseDefaultCredentials = false;
            client.Credentials = new System.Net.NetworkCredential("******@outlook.com", "****");
            client.Port = 587;
            client.Host = "smtp.office365.com";
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.EnableSsl = true;
            System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage("******@outlook.com", recEmail);       
            message.Subject = subject;
            message.Body = body;
            message.IsBodyHtml = true;
            message.Attachments.Add(new Attachment(new MemoryStream(attachments), recipient + ".pdf"));                    
            client.Send(message);
            ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Email sent.');", true);
            return true;          
        }
        int PageSize = 1;
      
        private void GetRecipient(int pageIndex)
        {
            using (SqlConnection con = new SqlConnection())
            {
                con.ConnectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
                try
                {
                    using (SqlCommand cmd = new SqlCommand("Recipients", con))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@CreatedBy", createby.Text.Trim());
                        cmd.Parameters.AddWithValue("@PageIndex", pageIndex);
                        cmd.Parameters.AddWithValue("@PageSize", PageSize);
                        cmd.Parameters.Add("@RecordCount", SqlDbType.Int, 4);
                        cmd.Parameters["@RecordCount"].Direction = ParameterDirection.Output;
                        con.Open();
                        using (SqlDataAdapter sda = new SqlDataAdapter())
                        {
                            cmd.Connection = con;
                            sda.SelectCommand = cmd;
                            using (DataTable dt = new DataTable())
                            {
                                sda.Fill(dt);
                                using (SqlDataReader dr = cmd.ExecuteReader())
                                    if (dr.HasRows)
                                    {
                                        GridView1.DataSource = dt;
                                        GridView1.DataBind();
                                    }
                                    else
                                    {
                                    }
                                int recordCount = Convert.ToInt32(cmd.Parameters["@RecordCount"].Value);
                                this.PopulatePager(recordCount, pageIndex);
                            }
                        }
                        con.Close();
                    }
                }
                catch (SqlException ex)
                {
                    string msg = "Error:";
                    msg += ex.Message;
                    throw new Exception(msg);
                }
            }
        }
        protected void Page_Changed(object sender, EventArgs e)
        {
            int pageIndex = int.Parse((sender as LinkButton).CommandArgument);
            this.GetRecipient(pageIndex);
        }
        private void PopulatePager(int recordCount, int currentPage)
        {
            double dblPageCount = (double)((decimal)recordCount / (decimal)PageSize);
            int pageCount = (int)Math.Ceiling(dblPageCount);
            List<System.Web.UI.WebControls.ListItem> pages = new List<System.Web.UI.WebControls.ListItem>();
            if (pageCount > 0)
            {
                if (currentPage != 1)
                {
                    pages.Add(new System.Web.UI.WebControls.ListItem("Prev", (currentPage - 1).ToString()));
                }
                if (pageCount < 4)
                {
                    for (int i = 1; i <= pageCount; i++)
                    {
                        pages.Add(new System.Web.UI.WebControls.ListItem(i.ToString(), i.ToString(), i != currentPage));
                    }
                }
                else if (currentPage < 4)
                {
                    for (int i = 1; i <= 4; i++)
                    {
                        pages.Add(new System.Web.UI.WebControls.ListItem(i.ToString(), i.ToString(), i != currentPage));
                    }
                    pages.Add(new System.Web.UI.WebControls.ListItem("...", (currentPage).ToString(), false));
                }
                else if (currentPage > pageCount - 4)
                {
                    pages.Add(new System.Web.UI.WebControls.ListItem("...", (currentPage).ToString(), false));
                    for (int i = currentPage - 1; i <= pageCount; i++)
                    {
                        pages.Add(new System.Web.UI.WebControls.ListItem(i.ToString(), i.ToString(), i != currentPage));
                    }
                }
                else
                {
                    pages.Add(new System.Web.UI.WebControls.ListItem("...", (currentPage).ToString(), false));
                    for (int i = currentPage - 2; i <= currentPage + 2; i++)
                    {
                        pages.Add(new System.Web.UI.WebControls.ListItem(i.ToString(), i.ToString(), i != currentPage));
                    }
                    pages.Add(new System.Web.UI.WebControls.ListItem("...", (currentPage).ToString(), false));
                }
                if (currentPage != pageCount)
                {
                    pages.Add(new System.Web.UI.WebControls.ListItem("Next", (currentPage + 1).ToString()));
                }
            }
            rptPager.DataSource = pages;
            rptPager.DataBind();

            lblPageIndex.Text = currentPage.ToString();
            lblTotalPage.Text = ((recordCount / PageSize) + ((recordCount % PageSize) > 0 ? 1 : 0)).ToString();
            lblTotal.Text = recordCount.ToString();
        }
        protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView1.PageIndex = e.NewPageIndex;
            this.GetRecipient(1);
        }
Developer technologies .NET Other
Developer technologies ASP.NET Other
Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Lan Huang-MSFT 30,186 Reputation points Microsoft External Staff
    2024-01-04T03:47:45.1533333+00:00

    Hi @Donald Symmons,

    But there are other pages in the Gridview, so will it also check the other checkboxes in other pages,

    Based on your description, you want to select all emails to be sent when the "Check All" checkbox is selected.

    You can use an ArrayList to store the checked checkbox and use ArrayList to ViewState to save the state of the checkbox.

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
            <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
            <div class="col-sm-11" style="width: 100%; margin: 0 auto; padding: 10px; margin-right: auto; margin-left: auto;">
                <asp:Label ID="createby" runat="server" Text="4"></asp:Label>
                <asp:UpdatePanel ID="panel" runat="server" ChildrenAsTriggers="true">
                    <ContentTemplate>
                        <div class="container-fluid p-3 mb5 bg-white rounded" id="card" style="margin: 0 auto; padding: 10px; border: 1.3px solid #e4e7e8;">
                            <asp:GridView ID="GridView1" runat="server" GridLines="None" DataKeyNames="Id" AllowPaging="true" HeaderStyle-BackColor="#fdfdfd" HeaderStyle-Font-Bold="false" HeaderStyle-ForeColor="#05214d" HeaderStyle-Font-Size="10pt" Font-Size="9pt"
                                AutoGenerateColumns="false" HeaderStyle-HorizontalAlign="left" RowStyle-HorizontalAlign="Left" OnPageIndexChanging="OnPageIndexChanging" class="table" Width="100%">
                                <EmptyDataTemplate>
                                    <div style="text-align: center; font-weight: 500; margin-top: 2%;">
                                        <i class="fal fa-file-times" style="margin: 0 auto; font-size: 30pt; color: #145c7c;"></i>
                                        <p id="P1" runat="server" style="font-size: 11pt; font-weight: 400;">No Recipient</p>
                                    </div>
                                </EmptyDataTemplate>
                                <Columns>
                                    <asp:TemplateField>
                                        <ItemTemplate>
                                            <asp:CheckBox ID="CheckSelected" runat="server" />
                                        </ItemTemplate>
                                        <HeaderTemplate>
                                            <asp:CheckBox ID="checkAll" OnCheckedChanged="check_CheckedChanged" AutoPostBack="true"
                                                runat="server" />
                                        </HeaderTemplate>
                                    </asp:TemplateField>
    
                                    <asp:BoundField DataField="Id" HeaderText="ID" HeaderStyle-Font-Bold="false" />
                                    <asp:BoundField DataField="Recipient" HeaderText="Recipients" HeaderStyle-Font-Bold="false" />
    
                                    <asp:TemplateField HeaderText="Email" HeaderStyle-Font-Bold="false">
                                        <ItemTemplate>
                                            <asp:HyperLink ID="emailLink" runat="server" Text='<%# Eval("RecEmail") %>' NavigateUrl='<%# Eval("RecEmail", "mailto:{0}") %>' />
                                        </ItemTemplate>
                                    </asp:TemplateField>
                                    <asp:TemplateField>
                                        <ItemTemplate>
                                            <asp:HiddenField ID="hfSeq" Value='<%# Eval("DocumentData") != System.DBNull.Value ? Convert.ToBase64String((byte[])Eval("DocumentData")) : string.Empty %>' runat="server" />
    
                                        </ItemTemplate>
                                    </asp:TemplateField>
    
                                    <asp:BoundField DataField="AwardDate" HeaderText="Date" HeaderStyle-Font-Bold="false" />
    
                                </Columns>
                            </asp:GridView>
    
                            <div style="float: right; font-size: 10pt; margin-right: 1%;">
                                Showing&nbsp;Page&nbsp;
            <asp:Label ID="lblPageIndex" runat="server" Text="Label" />
                                &nbsp;of&nbsp;
            <asp:Label ID="lblTotalPage" runat="server" />
                                (<asp:Label ID="lblTotal" runat="server" />
                                Records)&nbsp;&nbsp;
            <div class="dvPager">
                <asp:Repeater ID="rptPager" runat="server">
                    <ItemTemplate>
                        <asp:LinkButton ID="lnkPage" runat="server" Text='<%#Eval("Text") %>' CommandArgument='<%# Eval("Value") %>'
                            CssClass='<%# Convert.ToBoolean(Eval("Enabled")) ? "page_enabled" : "page_disabled" %>'
                            OnClick="Page_Changed" OnClientClick='<%# !Convert.ToBoolean(Eval("Enabled")) ? "return false;" : "" %>'></asp:LinkButton>
                    </ItemTemplate>
                </asp:Repeater>
            </div>
                            </div>
                            <br />
                            <br />
                        </div>
                    </ContentTemplate>
                </asp:UpdatePanel>
            </div>
            <div class="col-sm-10" style="width: 100%; margin: 0 auto; padding: 10px; padding-bottom: 10px;">
                <div class="row">
                    <div class="col-sm-11">
                        <div class="form-group">
                            <asp:Label CssClass="element" ID="Label1" runat="server">Subject</asp:Label>
                            <div class="input-group">
                                <asp:TextBox ID="TextSubject" runat="server" AutoCompleteType="None" Height="32" CssClass="form-control" placeholder="e.g Document File" />
                            </div>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-11">
                        <div class="form-group">
                            <div class="input-group">
                                <asp:TextBox ID="txtBody" runat="server" CssClass="form-control" Width="100%" Font-Size="10pt" TextMode="MultiLine" placeholder="e.g. Please download your documents below" Style="overflow: hidden; resize: none;" oninput="Resize(this)" />
                                <script type="text/javascript">
                                    function Resize(textbox) {
                                        textbox.style.height = "";
                                        textbox.style.height = Math.min(textbox.scrollHeight, 300) + "px";
                                    }
                                </script>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-11">
                        <div class="form-group">
                            <div class="input-group">
                                <asp:Button ID="SendBtn" CssClass="btn btn-primary" Text="Send Documents" runat="server" OnClick="SendBulkDocument" />
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </body>
    </html>
    
    
     protected void Page_Load(object sender, EventArgs e)
            {
                if (!this.IsPostBack)
                {
                    string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
                    using (SqlConnection con = new SqlConnection(constr))
                    {
                        using (SqlCommand cmd = new SqlCommand("SELECT * FROM DocumentTable"))
                        {
                            using (SqlDataAdapter sda = new SqlDataAdapter())
                            {
    
                                cmd.Connection = con;
                                sda.SelectCommand = cmd;
                                using (DataTable dt = new DataTable())
                                {
                                    sda.Fill(dt);
                                    ViewState["dt"] = dt;
                                    GridView1.DataSource = dt;
                                    GridView1.DataBind();
                                }
                            }
                        }
                    }
                    this.GetRecipient(1);
                }
            }
            protected void SendBulkDocument(object sender, EventArgs e)
            {
               
               
                //Create a temporary DataTable
                DataTable dtCustomers = new DataTable();
                dtCustomers.Columns.AddRange(new DataColumn[3] { new DataColumn("Recipient", typeof(string)),
                            new DataColumn("RecEmail", typeof(string)),
                            new DataColumn("DocumentData",typeof(string)) });
                //Copy the Checked Rows to DataTable
                foreach (GridViewRow row in GridView1.Rows)
                {
                    if (((CheckBox)GridView1.HeaderRow.Cells[0].FindControl("checkAll")).Checked)
                    {
                      
                        foreach (DataRow row1 in ((DataTable)ViewState["dt"]).Rows)
                        {
                            dtCustomers.Rows.Add(row1[1], row1[2], Convert.ToBase64String((byte[])row1[3]));
                        }
                    }
                    else if ((row.FindControl("CheckSelected") as CheckBox).Checked)
                    {
                        
                            dtCustomers.Rows.Add(row.Cells[2].Text, (row.FindControl("emailLink") as HyperLink).Text, (row.FindControl("hfSeq") as HiddenField).Value);
                        
                    }
                }
                    string subject = TextSubject.Text;
                string body = "Dear {0},<br /><br />" + txtBody.Text + "<br /><br />";
    
                for (int i = 0; i < dtCustomers.Rows.Count; i++)
                {
                    SendEmail(dtCustomers.Rows[i]["Recipient"].ToString(), dtCustomers.Rows[i]["RecEmail"].ToString(), subject, string.Format(body, dtCustomers.Rows[i]["Recipient"]), Convert.FromBase64String(dtCustomers.Rows[i]["DocumentData"].ToString()));
    
                }
    
    
            }
    
            private bool SendEmail(string recipient,string recEmail, string subject, string body, byte[] attachments)
            {
                SmtpClient client = new SmtpClient();
                client.UseDefaultCredentials = false;
                client.Credentials = new System.Net.NetworkCredential("***", "***");
                client.Port = 587;
                client.Host = "smtp.office365.com";
    
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                client.EnableSsl = true;
                System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage("******@outlook.com", recEmail);
            
    
                message.Subject = subject;
                message.Body = body;
                message.IsBodyHtml = true;
    
    
                message.Attachments.Add(new Attachment(new MemoryStream(attachments), recipient + ".pdf"));
               
                 
                client.Send(message);
                ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Email sent.');", true);
                return true;
            }
            int PageSize = 1;
          
            private void GetRecipient(int pageIndex)
            {
                using (SqlConnection con = new SqlConnection())
                {
                    con.ConnectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
                    try
                    {
                        using (SqlCommand cmd = new SqlCommand("Recipients", con))
                        {
                            cmd.CommandType = CommandType.StoredProcedure;
                            cmd.Parameters.AddWithValue("@CreatedBy", createby.Text.Trim());
                            cmd.Parameters.AddWithValue("@PageIndex", pageIndex);
                            cmd.Parameters.AddWithValue("@PageSize", PageSize);
                            cmd.Parameters.Add("@RecordCount", SqlDbType.Int, 4);
                            cmd.Parameters["@RecordCount"].Direction = ParameterDirection.Output;
                            con.Open();
                            using (SqlDataAdapter sda = new SqlDataAdapter())
                            {
                                cmd.Connection = con;
                                sda.SelectCommand = cmd;
                                using (DataTable dt = new DataTable())
                                {
                                    sda.Fill(dt);
                                    using (SqlDataReader dr = cmd.ExecuteReader())
                                        if (dr.HasRows)
                                        {
                                            GridView1.DataSource = dt;
                                            GridView1.DataBind();
                                        }
                                        else
                                        {
                                        }
                                    int recordCount = Convert.ToInt32(cmd.Parameters["@RecordCount"].Value);
                                    this.PopulatePager(recordCount, pageIndex);
                                }
                            }
                            con.Close();
                        }
                    }
                    catch (SqlException ex)
                    {
                        string msg = "Error:";
                        msg += ex.Message;
                        throw new Exception(msg);
                    }
                }
            }
            protected void Page_Changed(object sender, EventArgs e)
            {
                int pageIndex = int.Parse((sender as LinkButton).CommandArgument);
                this.GetRecipient(pageIndex);
                CheckData();
            }
            private void PopulatePager(int recordCount, int currentPage)
            {
                double dblPageCount = (double)((decimal)recordCount / (decimal)PageSize);
                int pageCount = (int)Math.Ceiling(dblPageCount);
                List<System.Web.UI.WebControls.ListItem> pages = new List<System.Web.UI.WebControls.ListItem>();
                if (pageCount > 0)
                {
                    if (currentPage != 1)
                    {
                        pages.Add(new System.Web.UI.WebControls.ListItem("Prev", (currentPage - 1).ToString()));
                    }
                    if (pageCount < 4)
                    {
                        for (int i = 1; i <= pageCount; i++)
                        {
                            pages.Add(new System.Web.UI.WebControls.ListItem(i.ToString(), i.ToString(), i != currentPage));
                        }
                    }
                    else if (currentPage < 4)
                    {
                        for (int i = 1; i <= 4; i++)
                        {
                            pages.Add(new System.Web.UI.WebControls.ListItem(i.ToString(), i.ToString(), i != currentPage));
                        }
                        pages.Add(new System.Web.UI.WebControls.ListItem("...", (currentPage).ToString(), false));
                    }
                    else if (currentPage > pageCount - 4)
                    {
                        pages.Add(new System.Web.UI.WebControls.ListItem("...", (currentPage).ToString(), false));
                        for (int i = currentPage - 1; i <= pageCount; i++)
                        {
                            pages.Add(new System.Web.UI.WebControls.ListItem(i.ToString(), i.ToString(), i != currentPage));
                        }
                    }
                    else
                    {
                        pages.Add(new System.Web.UI.WebControls.ListItem("...", (currentPage).ToString(), false));
                        for (int i = currentPage - 2; i <= currentPage + 2; i++)
                        {
                            pages.Add(new System.Web.UI.WebControls.ListItem(i.ToString(), i.ToString(), i != currentPage));
                        }
                        pages.Add(new System.Web.UI.WebControls.ListItem("...", (currentPage).ToString(), false));
                    }
                    if (currentPage != pageCount)
                    {
                        pages.Add(new System.Web.UI.WebControls.ListItem("Next", (currentPage + 1).ToString()));
                    }
                }
                rptPager.DataSource = pages;
                rptPager.DataBind();
    
                lblPageIndex.Text = currentPage.ToString();
                lblTotalPage.Text = ((recordCount / PageSize) + ((recordCount % PageSize) > 0 ? 1 : 0)).ToString();
                lblTotal.Text = recordCount.ToString();
            }
            private void PopulateGridByIndex(int index)
            {
                this.GridView1.PageIndex = index;
                this.GetRecipient(1);
                CheckData();
            }
           
            protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
            {
                PopulateGridByIndex(e.NewPageIndex);
                CheckData();
            }
    
            private void CheckData()
            {
                if (ViewState["CheckBoxArray"] != null)
                {
                    ArrayList CheckBoxArray = (ArrayList)ViewState["CheckBoxArray"];
                    string checkAllIndex = "chkAll-" + GridView1.PageIndex;
                    if (CheckBoxArray.IndexOf(checkAllIndex) != -1)
                    {
                        foreach (GridViewRow row in GridView1.Rows)
                        {
                            (row.FindControl("CheckSelected") as CheckBox).Checked = true;
                        }
                        CheckBox chkAll = (CheckBox)GridView1.HeaderRow.Cells[0].FindControl("checkAll");
                        chkAll.Checked = true;
                    }
                }
            }
            ArrayList CheckBoxArray = new ArrayList();
            protected void check_CheckedChanged(object sender, EventArgs e)
            {
                int tempIndex = -1;
                CheckBox headerCheckbox = (sender as CheckBox);
                bool checkedvalue = headerCheckbox.Checked;
                ViewState["Uncheck"] = checkedvalue;
                tempIndex = GridView1.PageIndex;
                int pageindex = tempIndex;
                for (int i = 0; i <= GridView1.PageCount; i++)
                {
                    if (i == GridView1.PageCount)
                    {
                        PopulateGridByIndex(0);
                    }
                    else
                    {
                        PopulateGridByIndex(i);
                    }
                    string checkAllIndex = "chkAll-" + GridView1.PageIndex;
                    if (checkedvalue)
                    {
                        CheckBoxArray.Add(checkAllIndex);
                    }
                    foreach (GridViewRow row in GridView1.Rows)
                    {
                        (row.FindControl("CheckSelected") as CheckBox).Checked = checkedvalue;
                    }
    
                    ((CheckBox)GridView1.HeaderRow.Cells[0].FindControl("checkAll")).Checked = checkedvalue;
                }
    
                ViewState["CheckBoxArray"] = CheckBoxArray;
    
            }
    
    

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


1 additional answer

Sort by: Most helpful
  1. Albert Kallal 5,586 Reputation points
    2024-01-04T19:51:31.4466667+00:00

    You have to persist the check box for each page.

    In other words, when a user clicks on a check box, you need/want to add to a "list" that you maintain. Since moving to the next/previous page will of course re-set all of the check boxes.

    In other words, a check all records will require you to maintain the list for each page (check all will ONLY work against the current page).

    So, here is a proof of concpet:

    Markup:

                <asp:GridView ID="GVHotels" runat="server" AutoGenerateColumns="False"
                    DataKeyNames="ID" CssClass="table table-hover" 
                    AllowPaging="True" PageSize="6"
                    OnPageIndexChanging="GVHotels_PageIndexChanging" OnRowDataBound="GVHotels_RowDataBound" >
                    <Columns>
                        <asp:BoundField DataField="FirstName" HeaderText="FirstName" />
                        <asp:BoundField DataField="LastName" HeaderText="LastName" />
                        <asp:BoundField DataField="City" HeaderText="City" />
                        <asp:BoundField DataField="HotelName" HeaderText="HotelName" />
                        <asp:BoundField DataField="Description" HeaderText="Description" />
                        <asp:TemplateField 
                            ItemStyle-HorizontalAlign="Center"
                            HeaderStyle-HorizontalAlign="Center" >
                            <ItemTemplate>
                                <asp:CheckBox ID="chkSel" runat="server" 
                                    OnCheckedChanged="chkSel_CheckedChanged"
                                    AutoPostBack="true" />
                            </ItemTemplate>
                            <HeaderTemplate>
                                <div style="text-align:center">
                                    Select All<br />
                                <asp:CheckBox ID="chkSelAll" runat="server"
                                    OnCheckedChanged="chkSelAll_CheckedChanged"
                                    AutoPostBack="true"
                                    />
                                </div>
                            </HeaderTemplate>
                        </asp:TemplateField>
                    </Columns>
                    <PagerStyle CssClass="GridPager" />
                </asp:GridView>
                <br />
                <asp:Button ID="cmdProcess" runat="server" Text="Process Selected"
                    CssClass="btn"
                    OnClick="cmdProcess_Click" />
            </div>
    
            <div style="float:left;margin-left:25px">
                <h3>To Process</h3>
                <asp:ListBox ID="ListBox1" runat="server"
                    DataValueField="ID"
                    DataTextField="HotelName"
                    width="300px" Height="400px">
                </asp:ListBox>
    
            </div>
    
    

    And code behind:

            List<int> MyCheckList = new List<int>();
            DataTable rstData = new DataTable();
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    rstData = General.MyRst("SELECT * FROM tblhotelsA ORDER BY HotelName");
                    Session["rstData"] = rstData;
                    Session["MyCheckList"] = MyCheckList;
                    LoadGrid();
                }
                else
                {
                    MyCheckList = (List<int>)Session["MyCheckList"];
                    rstData = (DataTable)Session["rstData"];
                }
            }
    
            void LoadGrid()
            {
                GVHotels.DataSource = rstData;
                GVHotels.DataBind();
            }
    
    
            protected void chkSel_CheckedChanged(object sender, EventArgs e)
            {
                CheckBox chkSel = (CheckBox)sender;
                GridViewRow gRow = (GridViewRow)chkSel.NamingContainer; // get gridRow
                int PK = (int)GVHotels.DataKeys[gRow.RowIndex]["ID"];
    
                if (chkSel.Checked)             // add or remove PK id
                    MyCheckList.Add(PK);
                else
                    MyCheckList.Remove(PK);
    
                CheckBox chkSelAll = (CheckBox)GVHotels.HeaderRow.FindControl("chkSelAll");
                chkSelAll.Checked = false; // always UN check if user changed one row
            }
    
            protected void chkSelAll_CheckedChanged(object sender, EventArgs e)
            {
                CheckBox chkSelAll = (CheckBox)sender;  
                bool MyChecked = chkSelAll.Checked;
                MyCheckList.Clear();
                if (MyChecked)
                {
                    foreach (DataRow dr in rstData.Rows)
                        MyCheckList.Add((int)dr["ID"]);
                }
                LoadGrid();
                chkSelAll = (CheckBox)GVHotels.HeaderRow.FindControl("chkSelAll");
                chkSelAll.Checked = MyChecked;
    
            }
    
            protected void GVHotels_PageIndexChanging(object sender, GridViewPageEventArgs e)
            {
                GVHotels.PageIndex = e.NewPageIndex;
                LoadGrid();
            }
    
            protected void GVHotels_RowDataBound(object sender, GridViewRowEventArgs e)
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    int PK = (int)GVHotels.DataKeys[e.Row.RowIndex]["ID"];
                    CheckBox chkSel = (CheckBox)e.Row.FindControl("chkSel");
                    chkSel.Checked = MyCheckList.Contains(PK);
                }
            }
    
            protected void cmdProcess_Click(object sender, EventArgs e)
            {
                if (MyCheckList.Count > 0)
                {
                    string strSQL =
                        "SELECT * FROM tblHotelsA WHERE " +
                        "ID IN (" + string.Join(",", MyCheckList.ToArray()) + ") " +
                        "ORDER BY HotelName";
                    ListBox1.DataSource = General.MyRst(strSQL);
                    ListBox1.DataBind();
                }
            }
    
    

    And the result looks like this:

    checkboxlist

    So, it not a lot of code, but do note how we used server side code for this.

    Study the above, as it shows how to keep/track/persist the checked rows. And note the final button click showing the selected PK values.

    So a check all? Rather easy. but now go to say the 2nd or 3rd page and un-check ONE value. So, one can check a few boxes - on any pages, and paging to that page will continue to show the correct rows checked. This includes a user who no doubt will use check all, and then decide to un-check a few records on any pages they move to. Thus for this to work - a list of checked rows (PK id list) has to be maintained for this to work.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.