Now here in this tutorial, I’ll explain how you can send gridview selected rows in mail body from code-behind or server-side in asp.net using c# or vb.net with example code and step by step guide.
In my previous tutorials, I’d explained exporting gridview data to word excel text or pdf, get gridview selected row hiddenfield value using jquery, print gridview data on print button click and other more cracking tutorials on GridView, Asp.net here.
To send selected or checked rows as email body, first you need to add one asp.net button control to .aspx page:
<asp:Button ID="btnSendMail" runat="server" Text="Send Mail" OnClick="btnSendMail_Click" />
As you see, I added OnClick=”btnSendMail_Click” event to send grid view selected rows as email body. Now choose your language (that is C# or Vb.net) and add the following code to your code-behind file.
Function To Send GridView Selected Rows in Mail Body in Asp.net
I guess you all know about how to send email in asp.net. Also check out my previous tutorial on how to send gridview data within email body in asp.net here. Following is the function that allows you to send only gridview selected rows in email.
If you are using C# as code-behind, then use the following code:
First add the following namespace:
using System.Net.Mail; using System.IO; using System.Text;
After that add the following code in .aspx.cs code-behind file to send gridview selected rows in mail body:
private string GridViewToHtml(GridView grdResultDetails) { SaveCheckedStates(); grdResultDetails.AllowPaging = false; LoadGridData(); StringBuilder objSB = new StringBuilder(); StringWriter objSW = new StringWriter(objSB); HtmlTextWriter objHW = new HtmlTextWriter(objSW); if (ViewState["SELECTED_ROWS"] != null) { ArrayList objSelectedRowsAL = (ArrayList)ViewState["SELECTED_ROWS"]; for (int j = 0; j < grdResultDetails.Rows.Count; j++) { GridViewRow row = grdResultDetails.Rows[j]; int rowIndex = Convert.ToInt32(grdResultDetails.DataKeys[row.RowIndex].Value); if (!objSelectedRowsAL.Contains(rowIndex)) { //make invisible because row is not checked row.Visible = false; } } } grdResultDetails.RenderControl(objHW); return objSB.ToString(); } protected void btnSendMail_Click(object sender, EventArgs e) { try { string Subject = "This is test mail with gridview data", Body = GridViewToHtml(grdResultDetails), ToEmail = "toemail@domain.com"; string SMTPUser = "email@domain.com", SMTPPassword = "password"; //Now instantiate a new instance of MailMessage MailMessage mail = new MailMessage(); //set the sender address of the mail message mail.From = new System.Net.Mail.MailAddress(SMTPUser, "AspnetO"); //set the recepient addresses of the mail message mail.To.Add(ToEmail); //set the subject of the mail message mail.Subject = Subject; //set the body of the mail message mail.Body = Body; //leave as it is even if you are not sending HTML message mail.IsBodyHtml = true; //set the priority of the mail message to normal mail.Priority = System.Net.Mail.MailPriority.Normal; //instantiate a new instance of SmtpClient SmtpClient smtp = new SmtpClient(); //if you are using your smtp server, change your host like "smtp.yourdomain.com" smtp.Host = "smtp.gmail.com"; //change your port for your host smtp.Port = 25; //or you can also use port# 587 //provide smtp credentials to authenticate to your account smtp.Credentials = new System.Net.NetworkCredential(SMTPUser, SMTPPassword); //if you are using secure authentication using SSL/TLS then "true" else "false" smtp.EnableSsl = true; smtp.Send(mail); lblMsg.Text = "Success: Mail sent successfully!"; lblMsg.ForeColor = System.Drawing.Color.Green; } catch (SmtpException ex) { //catched smtp exception lblMsg.Text = "SMTP Exception: " + ex.Message.ToString(); lblMsg.ForeColor = System.Drawing.Color.Red; } catch (Exception ex) { lblMsg.Text = "Error: " + ex.Message.ToString(); lblMsg.ForeColor = System.Drawing.Color.Red; } }
If you are using Vb.net as code-behind, then use following code:
First add the following namespace:
Imports System.Net.Mail Imports System.IO
After that add the following code in .aspx.vb code-behind file to send gridview selected rows in mail body:
Private Function GridViewToHtml(ByVal grdResultDetails As GridView) As String SaveCheckedStates() grdResultDetails.AllowPaging = False LoadGridData() Dim objSB As New StringBuilder() Dim objSW As New StringWriter(objSB) Dim objHW As New HtmlTextWriter(objSW) If ViewState("SELECTED_ROWS") IsNot Nothing Then Dim objSelectedRowsAL As ArrayList = CType(ViewState("SELECTED_ROWS"), ArrayList) For j As Integer = 0 To grdResultDetails.Rows.Count - 1 Dim row As GridViewRow = grdResultDetails.Rows(j) Dim rowIndex As Integer = Convert.ToInt32(grdResultDetails.DataKeys(row.RowIndex).Value) If Not objSelectedRowsAL.Contains(rowIndex) Then 'make invisible because row is not checked' row.Visible = False End If Next j End If grdResultDetails.RenderControl(objHW) Return objSB.ToString() End Function Protected Sub btnSendMail_Click(ByVal sender As Object, ByVal e As EventArgs) Try Dim Subject As String = "This is test mail with gridview data", Body As String = GridViewToHtml(grdResultDetails), ToEmail As String = "toemail@domain.com" Dim SMTPUser As String = "email@domain.com", SMTPPassword As String = "password" 'Now instantiate a new instance of MailMessage' Dim mail As New MailMessage() 'set the sender address of the mail message' mail.From = New System.Net.Mail.MailAddress(SMTPUser, "AspnetO") 'set the recepient addresses of the mail message' mail.To.Add(ToEmail) 'set the subject of the mail message' mail.Subject = Subject 'set the body of the mail message' mail.Body = Body 'leave as it is even if you are not sending HTML message' mail.IsBodyHtml = True 'set the priority of the mail message to normal' mail.Priority = System.Net.Mail.MailPriority.Normal 'instantiate a new instance of SmtpClient' Dim smtp As New SmtpClient() 'if you are using your smtp server, then change your host like "smtp.yourdomain.com"' smtp.Host = "smtp.gmail.com" 'change your port for your host' smtp.Port = 25 'or you can also use port# 587 'provide smtp credentials to authenticate to your account' smtp.Credentials = New System.Net.NetworkCredential(SMTPUser, SMTPPassword) 'if you are using secure authentication using SSL/TLS then "true" else "false"' smtp.EnableSsl = True smtp.Send(mail) lblMsg.Text = "Success: Mail sent successfully!" lblMsg.ForeColor = System.Drawing.Color.Green Catch ex As SmtpException 'catched smtp exception' lblMsg.Text = "SMTP Exception: " & ex.Message.ToString() lblMsg.ForeColor = System.Drawing.Color.Red Catch ex As Exception lblMsg.Text = "Error: " & ex.Message.ToString() lblMsg.ForeColor = System.Drawing.Color.Red End Try End Sub
During development, you may face following errors:
Control ‘grdResultDetails’ of type ‘GridView’ must be placed inside a form tag with runat=server
Control ‘grdResultDetails’ of type ‘GridView’ must be placed inside a form tag with
runat=server.
Description: An unhandled exception occurred during the execution of the current web request.
Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: Control ‘grdResultDetails’ of type ‘GridView’ must be placed inside a form tag with runat=server.
To resolve this issue, please check how to solve control ‘grdResultDetails’ of type ‘GridView’ must be placed inside a form tag with runat=server.
RegisterForEventValidation can only be called during Render();
RegisterForEventValidation can only be called during Render();
Description: An unhandled exception occurred during the execution of the current web request.
Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: RegisterForEventValidation can only be called during Render();
To resolve this issue, please check how to solve RegisterForEventValidation can only be called during Render();.
Example Result And Code
You can download complete sample code and get more details about this tutorial here.