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 Page
<asp:Label ID="lblPageIndex" runat="server" Text="Label" />
of
<asp:Label ID="lblTotalPage" runat="server" />
(<asp:Label ID="lblTotal" runat="server" />
Records)
<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.