Link to home
Start Free TrialLog in
Avatar of newjeep19
newjeep19Flag for United States of America

asked on

Sending only one email for a gridview row when muliplle rows are selected via a checkbox

I have a grid that when a checkbox or checkboxes in the rows in the grid are checked then an email is generated. However, I am getting an email sent when every row is checked. So, if there is a grid that has six rows and three of the rows checkboxes are checked then i get three emails instead of one email that shows all three checked rows.
The code is below:
C# Code:
 // ACTION email :  Email to Service Support Team using Windows Authentication
                try
                {

                    // Html output buffer.
                    StringBuilder sbHtml = new StringBuilder();

                    using (StringWriter sw = new StringWriter(sbHtml))
                    {
                        using (HtmlTextWriter hw = new HtmlTextWriter(sw))
                        {
                            // Set the custom render method for all the controls inside GridView (gvParent).
                            SetMyCustomRenderMethodDelegate(hw, gvParent);

                            // Render GridView (gvParent) into a string builder.
                            gvParent.RenderControl(hw);
                        }
                    }

                    // Declare a string variable to hold senders email
                    string senderAddress = Request.ServerVariables["LOGON_USER"].ToString().Split('\\')[1];

                    // If sender is null, then user not found or has no email address
                    if (senderAddress == null)
                    {
                        lblMessage.Text = "Your user account was not found, or you have no email address - email message not sent.";
                        lblMessage.ForeColor = System.Drawing.Color.Red;
                        return;
                    }

                   foreach (GridViewRow gr in gvParent.Rows)
                   {
                        Label txtVendor = (Label)gr.FindControl("txtVendor");
                        Label txtGTRIPONumb = (Label)gr.FindControl("txtGTRIPONumb");
                        CheckBox cb = (CheckBox)gr.FindControl("chkRequestSNT");
                        HiddenField hfCustomer = (HiddenField)gr.FindControl("AccountIdNameID"); 
                        if (cb.Checked)
                        {
                            MailMessage mailIAM = new MailMessage();

                            mailIAM.From = new MailAddress(senderAddress + "@company.com");
                            mailIAM.To.Add("servicesupport@company.com");
                            mailIAM.Subject = "Request SNT for: " + "Customers(s) : " + hfCustomer.Value.ToString();  //"Vendor(s) : " + txtVendor.Text + " " + "|" + " " + "GTRI PO # : " + txtGTRIPONumb.Text + " " + "|"  " + 
                            mailIAM.IsBodyHtml = true;
                            mailIAM.BodyEncoding = System.Text.Encoding.UTF32; 
                            string url = string.Format("http://crm/{0}/sfa/salesorder/edit.aspx?id={1}",crmOrganization,_orderId);
                            mailIAM.Body = sbHtml.ToString() + @"<br/>Link to Order : <a href='" + url + "'>CRM Order</a>"; 
                                                                                                                
                            System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
                            smtp.Host = "company.com";
                            smtp.Port = 25;
                            smtp.Send(mailIAM);
                        }
                        else
                        {
                            CheckBox chk = (CheckBox)gr.FindControl("chkSNTOrder");
                            if (chk.Checked)
                            {
                                MailMessage mailIAM = new MailMessage();

                                mailIAM.From = new MailAddress(senderAddress + "@company.com");
                                mailIAM.To.Add("servicesupport@company.com");
                                mailIAM.Subject = "SNT Order for: " + "Customers(s) : " + hfCustomer.Value.ToString(); 
                                mailIAM.IsBodyHtml = true;
                                mailIAM.BodyEncoding = System.Text.Encoding.UTF32;
                                string url = string.Format("http://crm/{0}/sfa/salesorder/edit.aspx?id={1}", crmOrganization, _orderId);
                                mailIAM.Body = sbHtml.ToString() + @"<br/>Link to Order : <a href='" + url + "'>CRM Order</a>"; 
                                System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
                                smtp.Host = "company.com";
                                smtp.Port = 25;
                                smtp.Send(mailIAM);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    lblMessage.Text = "An error occurred sending your e-mail, the error is:\r\n" + ex.Message;
                    lblMessage.ForeColor = System.Drawing.Color.Red;
                    return;
                }

  // Helper method.
        void SetMyCustomRenderMethodDelegate(HtmlTextWriter writer, Control control)
        {
            if (control is GridViewRow)
                control.SetRenderMethodDelegate(MyCustomRender);

            foreach (Control childControl in control.Controls)
            {
                SetMyCustomRenderMethodDelegate(writer, childControl);
            }
        }

        // ********************* DO NOT DELETE ********************** \\
        // Required to avoid the "GridView must be placed inside a form tag with runat=server" error.
        public override void VerifyRenderingInServerForm(Control control)
        {
            return;
        }

        #region Misc Function
        //FUNCTION : Checks if the checkbox is checked in the grideview row and retrieve all the selected items in the GridView.
        // Excludes hidden rows, checkboxes and buttons in the gridview.
        void MyCustomRender(HtmlTextWriter writer, Control control)
        {
            // Remove the delegate to avoid infinite loop.
            control.SetRenderMethodDelegate(null);

            if (control is TableRow)
            {
                TableRow row = (TableRow)control;

                // Logic to render only the checked rows.
                CheckBox cb = control.FindControl("chkRequestSNT") as CheckBox;
                CheckBox chk = control.FindControl("chkSNTOrder") as CheckBox;
                int index = 0;
                foreach (TableCell item in row.Cells)
                {
                    index++;
                    switch (index)
                    {

                        case 1:
                        case 13:
                            //Ignore column 1 and 13
                            continue;
                        default:
                            if (cb == null || chk == null || cb.Checked || chk.Checked)

                                item.RenderControl(writer);
                            break;
                    }
                }
            }
            else
            {
                control.RenderControl(writer);
            }
        }

Open in new window


Please help
Avatar of volking
volking

           /* first, build the email body */
            StringBuilder sb = new StringBuilder();
            foreach (GridViewRow gr in gvParent.Rows)
            {
                sb.Append(sbHtml.ToString() + @"<br/>Link to Order : <a href='" + url + "'>CRM Order</a>");
            }

            /* then send one email */
            MailMessage mailIAM = new MailMessage();
            mailIAM.From = new MailAddress(senderAddress + "@company.com");
            mailIAM.To.Add("servicesupport@company.com");
            mailIAM.Subject = "SNT Order for: " + "Customers(s) : " + hfCustomer.Value.ToString();
            mailIAM.IsBodyHtml = true;
            mailIAM.BodyEncoding = System.Text.Encoding.UTF32;
            string url = string.Format("http://crm/{0}/sfa/salesorder/edit.aspx?id={1}", crmOrganization, _orderId);
            mailIAM.Body = sb.ToString()
            System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
            smtp.Host = "company.com";
            smtp.Port = 25;
            smtp.Send(mailIAM);
Avatar of newjeep19

ASKER

I get these error message from this line
sb.Append(sbHtml.ToString() + @"<br/>Link to Order : <a href='" + url + "'>CRM Order</a>");

The name 'url' does not exist in the current context      
The name 'sbHtml' does not exist in the current context

Why?      
Also I fixed the error and I still get two emails sent when two checkboxes are checked in two seperate rows.....did not work ...please help
 Replace your code with Below

Code to be replaced :
foreach (GridViewRow gr in gvParent.Rows)
                   {
                        Label txtVendor = (Label)gr.FindControl("txtVendor");
                        Label txtGTRIPONumb = (Label)gr.FindControl("txtGTRIPONumb");
                        CheckBox cb = (CheckBox)gr.FindControl("chkRequestSNT");
                        HiddenField hfCustomer = (HiddenField)gr.FindControl("AccountIdNameID");
                        if (cb.Checked)
                        {
                            MailMessage mailIAM = new MailMessage();

                            mailIAM.From = new MailAddress(senderAddress + "@company.com");
                            mailIAM.To.Add("servicesupport@company.com");
                            mailIAM.Subject = "Request SNT for: " + "Customers(s) : " + hfCustomer.Value.ToString();  //"Vendor(s) : " + txtVendor.Text + " " + "|" + " " + "GTRI PO # : " + txtGTRIPONumb.Text + " " + "|"  " +
                            mailIAM.IsBodyHtml = true;
                            mailIAM.BodyEncoding = System.Text.Encoding.UTF32;
                            string url = string.Format("http://crm/{0}/sfa/salesorder/edit.aspx?id={1}",crmOrganization,_orderId);
                            mailIAM.Body = sbHtml.ToString() + @"<br/>Link to Order : <a href='" + url + "'>CRM Order</a>";
                                                                                                               
                            System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
                            smtp.Host = "company.com";
                            smtp.Port = 25;
                            smtp.Send(mailIAM);
                        }
                        else
                        {
                            CheckBox chk = (CheckBox)gr.FindControl("chkSNTOrder");
                            if (chk.Checked)
                            {
                                MailMessage mailIAM = new MailMessage();

                                mailIAM.From = new MailAddress(senderAddress + "@company.com");
                                mailIAM.To.Add("servicesupport@company.com");
                                mailIAM.Subject = "SNT Order for: " + "Customers(s) : " + hfCustomer.Value.ToString();
                                mailIAM.IsBodyHtml = true;
                                mailIAM.BodyEncoding = System.Text.Encoding.UTF32;
                                string url = string.Format("http://crm/{0}/sfa/salesorder/edit.aspx?id={1}", crmOrganization, _orderId);
                                mailIAM.Body = sbHtml.ToString() + @"<br/>Link to Order : <a href='" + url + "'>CRM Order</a>";
                                System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
                                smtp.Host = "company.com";
                                smtp.Port = 25;
                                smtp.Send(mailIAM);
                            }
                        }
                    }




Code to replace with:


                   string url = "";
                   foreach (GridViewRow gr in gvParent.Rows)
                   {
                        Label txtVendor = (Label)gr.FindControl("txtVendor");
                        Label txtGTRIPONumb = (Label)gr.FindControl("txtGTRIPONumb");
                        CheckBox cb = (CheckBox)gr.FindControl("chkRequestSNT");
                        HiddenField hfCustomer = (HiddenField)gr.FindControl("AccountIdNameID");
                        if (cb.Checked)
                        {
                            url=string.Format("http://crm/{0}/sfa/salesorder/edit.aspx?id={1}",crmOrganization,_orderId);
                            sbHtml=sbHtml.ToString() + @"<br/>Link to Order : <a href='" + url + "'>CRM Order</a>";
                        }
                        else
                        {
                            CheckBox chk = (CheckBox)gr.FindControl("chkSNTOrder");
                            if (chk.Checked)
                            {                              
                                 url= string.Format("http://crm/{0}/sfa/salesorder/edit.aspx?id={1}", crmOrganization, _orderId);  
                                sbHtml=sbHtml.ToString() + @"<br/>Link to Order : <a href='" + url + "'>CRM Order</a>";
                            }
                        }
                    }
                    MailMessage mailIAM = new MailMessage();
                    mailIAM.From = new MailAddress(senderAddress + "@company.com");
                    mailIAM.To.Add("servicesupport@company.com");
                    mailIAM.Subject = "Request SNT for: " + "Customers(s) : " + hfCustomer.Value.ToString();  //"Vendor(s) : " + txtVendor.Text + " " + "|" + " " + "GTRI PO # : " + txtGTRIPONumb.Text + " " + "|"  " +
                    mailIAM.IsBodyHtml = true;
                    mailIAM.BodyEncoding = System.Text.Encoding.UTF32;
                    mailIAM.Body =  sbHtml;                                  
                    System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
                    smtp.Host = "company.com";
                    smtp.Port = 25;
                    smtp.Send(mailIAM);
Thanks for your reply but now instead of geting two emails because two of the checkboxes where checked in two different rows I am getting an email for all of the rows. So If the Grid has 6 rows and even though two of those rows have checkboxes that are checked I get six emails when all I want is to get one email sent even when the two or three or etc... have rows with checkboxes checked. Please help - Thank you
can you please upload ur page code. .cs file?
Code: c#
 // ACTION email :  Email to Service Support Team using Windows Authentication
                try
                {
                    // Declare a string variable to hold senders email
                    string senderAddress = Request.ServerVariables["LOGON_USER"].ToString().Split('\\')[1];

                    // If sender is null, then user not found or has no email address
                    if (senderAddress == null)
                    {
                        lblMessage.Text = "Your user account was not found, or you have no email address - email message not sent.";
                        lblMessage.ForeColor = System.Drawing.Color.Red;
                        return;
                    }

                   //  Html output buffer.
                    StringBuilder sbHtml = new StringBuilder();

                    using (StringWriter sw = new StringWriter(sbHtml))
                    {
                        using (HtmlTextWriter hw = new HtmlTextWriter(sw))
                        {
                            // Set the custom render method for all the controls inside GridView (gvParent).
                            SetMyCustomRenderMethodDelegate(hw, gvParent);

                            // Render GridView (gvParent) into a string builder.
                            gvParent.RenderControl(hw);
                        }

                        string url = "";
                        foreach (GridViewRow gr in gvParent.Rows)
                        {
                            //Label txtVendor = (Label)gr.FindControl("txtVendor");
                            //Label txtGTRIPONumb = (Label)gr.FindControl("txtGTRIPONumb");
                            CheckBox cb = (CheckBox)gr.FindControl("chkRequestSNT");
                            HiddenField hfCustomer = (HiddenField)gr.FindControl("AccountIdNameID");
                            if (cb.Checked)
                            {
                                url = string.Format("http://crm/{0}/sfa/salesorder/edit.aspx?id={1}", crmOrganization, _orderId);
                                sbHtml = sbHtml.ToString(); // +@"<br/>Link to Order : <a href='" + url + "'>CRM Order</a>";
                            }
                            else
                            {
                                CheckBox chk = (CheckBox)gr.FindControl("chkSNTOrder");
                                if (chk.Checked)
                                {
                                    url = string.Format("http://crm/{0}/sfa/salesorder/edit.aspx?id={1}", crmOrganization, _orderId);
                                    sbHtml = sbHtml.ToString() + @"<br/>Link to Order : <a href='" + url + "'>CRM Order</a>";
                                }
                            }


                            MailMessage mailIAM = new MailMessage();

                            mailIAM.From = new MailAddress(senderAddress + "@company.com");
                             mailIAM.To.Add("servicesupport@company.com");
                            
                            mailIAM.Subject = "Request SNT for: " + "Customers(s) : " + hfCustomer.Value.ToString();  //"Vendor(s) : " + txtVendor.Text + " " + "|" + " " + "GTRI PO # : " + txtGTRIPONumb.Text + " " + "|"  " + 
                            mailIAM.IsBodyHtml = true;
                            mailIAM.BodyEncoding = System.Text.Encoding.UTF32;
                            mailIAM.Body = sbHtml.ToString();// +@"<br/>Link to Order : <a href='" + url + "'>CRM Order</a>";
                            System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
                            smtp.Host = "company.com";
                            smtp.Port = 25;
                            smtp.Send(mailIAM);
                        }
                    }

                }
                catch (Exception ex)
                {
                    lblMessage.Text = "An error occurred sending your e-mail, the error is:\r\n" + ex.Message;
                    lblMessage.ForeColor = System.Drawing.Color.Red;
                    return;
                }

  // Helper method.
        void SetMyCustomRenderMethodDelegate(HtmlTextWriter writer, Control control)
        {
            if (control is GridViewRow)
                control.SetRenderMethodDelegate(MyCustomRender);

            foreach (Control childControl in control.Controls)
            {
                SetMyCustomRenderMethodDelegate(writer, childControl);
            }
        }

        // ********************* DO NOT DELETE ********************** \\
        // Required to avoid the "GridView must be placed inside a form tag with runat=server" error.
        public override void VerifyRenderingInServerForm(Control control)
        {
            return;
        }

        #region Misc Function
        //FUNCTION : Checks if the checkbox is checked in the grideview row and retrieve all the selected items in the GridView. Excludes hidden rows, checkboxes and buttons in the gridview.
        void MyCustomRender(HtmlTextWriter writer, Control control)
        {
            // Remove the delegate to avoid infinite loop.
            control.SetRenderMethodDelegate(null);

            if (control is TableRow)
            {
                TableRow row = (TableRow)control;

                // Logic to render only the checked rows.
                CheckBox cb = control.FindControl("chkRequestSNT") as CheckBox;
                CheckBox chk = control.FindControl("chkSNTOrder") as CheckBox;
                int index = 0;
                foreach (TableCell item in row.Cells)
                {
                    index++;
                    switch (index)
                    {
                        case 1:
                        case 13:
                            //Ignore column 1 and 13
                            continue;
                        default:
                            if (cb == null || chk == null || cb.Checked || chk.Checked)

                                item.RenderControl(writer);
                            break;
                    }
                }
            }
            else
            {
                control.RenderControl(writer);
            }
        }

Open in new window

write mail sending code outside of foreach loop
Sorry please explain........or demo with the code above (that i sent)
I get this error:
   Cannot implicitly convert type 'string' to 'System.Text.StringBuilder'
here:
  sbHtml = sbHtml.ToString() + @"<br/>Link to Order : <a href='" + url + "'>CRM Order</a>";
 and this error:
    Cannot implicitly convert type 'System.Text.StringBuilder' to 'string'
here:
mailIAM.Body = sbHtml;      
When I fixed the probllem above by doing this:  However, I still multiple emails sent  when Ihave only two checkboxes checked........I only want one email sent and only contain the two rows that have the checkbox checked in the Grid. Please hel;p......need resolution

//  Html output buffer.
                    StringBuilder sbHtml = new StringBuilder();

                    String Htmlsb;

                    using (StringWriter sw = new StringWriter(sbHtml))
                    {
                        using (HtmlTextWriter hw = new HtmlTextWriter(sw))
                        {
                            // Set the custom render method for all the controls inside GridView (gvParent).
                            SetMyCustomRenderMethodDelegate(hw, gvParent);

                            // Render GridView (gvParent) into a string builder.
                            gvParent.RenderControl(hw);
                        }


string url = "";
                        foreach (GridViewRow gr in gvParent.Rows)
                        {
                            CheckBox cb = (CheckBox)gr.FindControl("chkRequestSNT");
                            HiddenField hfCustomer = (HiddenField)gr.FindControl("AccountIdNameID");
                            if (cb.Checked)
                            {
                                url = string.Format("http://crm/{0}/sfa/salesorder/edit.aspx?id={1}", crmOrganization, _orderId);
                                Htmlsb = sbHtml.ToString() + @"<br/>Link to Order : <a href='" + url + "'>CRM Order</a>";
                            }
                            else
                            {
                                CheckBox chk = (CheckBox)gr.FindControl("chkSNTOrder");
                                if (chk.Checked)
                                {
                                    url = string.Format("http://crm/{0}/sfa/salesorder/edit.aspx?id={1}", crmOrganization, _orderId);
                                    Htmlsb = sbHtml.ToString() + @"<br/>Link to Order : <a href='" + url + "'>CRM Order</a>";
                                }
                            }


                            MailMessage mailIAM = new MailMessage();

                            mailIAM.From = new MailAddress(senderAddress + "@gtri.com");
                            // mailIAM.To.Add("servicesupport@gtri.com");
                            mailIAM.To.Add("remerson@gtri.com");
                            mailIAM.Subject = "Request SNT for: " + "Customers(s) : " + hfCustomer.Value.ToString();  //"Vendor(s) : " + txtVendor.Text + " " + "|" + " " + "GTRI PO # : " + txtGTRIPONumb.Text + " " + "|"  " +
                            mailIAM.IsBodyHtml = true;
                            mailIAM.BodyEncoding = System.Text.Encoding.UTF32;
                            mailIAM.Body = Htmlsb;// +@"<br/>Link to Order : <a href='" + url + "'>CRM Order</a>";
                            System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
                            smtp.Host = "webmail.gtrint.com";
                            smtp.Port = 25;
                            smtp.Send(mailIAM);
                        }
                    }

ASKER CERTIFIED SOLUTION
Avatar of newjeep19
newjeep19
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I've requested that this question be closed as follows:

Accepted answer: 0 points for newjeep19's comment http:/Q_27437929.html#37110572

for the following reason:

Found my only very simple solution
Found my only very simple solution
found my own solution
What is the Solution.. Can you please share with us? I think, I have provided you with the solution.
I thank you for your help but the solution I found without changing my code: I only needed to add a break; look below:
Code:
 MailMessage mailIAM = new MailMessage();

                                mailIAM.From = new MailAddress(senderAddress + "@company.com");
                                mailIAM.To.Add("servicesupport@company.com");
                                mailIAM.Subject = "SNT Order for: " + "Customers(s) : " + hfCustomer.Value.ToString();
                                mailIAM.IsBodyHtml = true;
                                mailIAM.BodyEncoding = System.Text.Encoding.UTF32;
                                string url = string.Format("http://crm/{0}/sfa/salesorder/edit.aspx?id={1}", crmOrganization, _orderId);
                                mailIAM.Body = sbHtml.ToString() + @"<br/>Link to Order : <a href='" + url + "'>CRM Order</a>";
                                System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
                                smtp.Host = "company.com";
                                smtp.Port = 25;
                                smtp.Send(mailIAM);
                                 
                                  break;
your code will send one mail with link to only one order. Anyways my code is also correct one so i have posted objection.
That was not what i wanted so i will protest your protest. If you look at my question I wanted one email sent for just one order that contains multiple rows in the grid and only bring back the rows that have a checkbox checked. Again, I appricate your help but i did find the resolution on my own.