AspnetO

We code, that works!

  • Home
  • Asp.net
  • MVC
  • Interview Questions
You are here: Home / Asp.net / Send Asp.net GridView Data in smtp Mail in Asp.net C# Vb.net

Send Asp.net GridView Data in smtp Mail in Asp.net C# Vb.net

By: Mayank Modi | Falls In: Asp.net, C#, VB | Last Updated: Oct 10, 2020

Now here in this tutorial, I’ll explain how you can send asp.net gridview data in mail/email with its data in asp.net, c#, vb.net using gmail smtp settings.

In my previous tutorials, I’d explained how to send test mail using gmail smtp settings, how to export gridview selected rows to word excel text and pdf, how to send html web page as email and other more cracking tutorials on Asp.net, JavaScript, jQuery here.

 

The .NET framework has built-in namespace for handling email settings, which is System.Net.Mail namespace. In the following example, I’ll use two classes from the System.Net.Mail namespace:

  • For email settings, we will use the MailMessage class and
  • For smtp settings and sending email, we will use the SmtpClient class

I guess you all know how to send mails via SMTP server, if not then please follow my first tutorial about how to send test mail using gmail smtp settings here.

ASP.net Gridview Data

HTML Markup – [.aspx]

Following is the complete HTML markup code for your .aspx page:

<html xmlns=”http://www.w3.org/1999/xhtml”>
<head id=”Head1″ runat=”server”>
<title>Send asp.net gridview in mail in c#, vb.net</title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<table>
<tr>
<td colspan=”2″>
<h4>Send asp.net gridview result in mail in c#, vb.net</h4>
</td>
</tr>
<tr>
<td>
<asp:TextBox ID=”txtToEmail” runat=”server” Width=”215″ Height=”25″
placeholder=”To email: example@example.com”></asp:TextBox>
<asp:RequiredFieldValidator ID=”rfvToEmail” runat=”server” ErrorMessage=”Required”
ControlToValidate=”txtToEmail” ForeColor=”Red” Display=”Dynamic”>
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID=”revToEmail” runat=”server” ForeColor=”Red”
ValidationExpression=”\w+([-+.’]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*”
ControlToValidate=”txtToEmail” ErrorMessage=”Invalid Email”>
</asp:RegularExpressionValidator>
</td>
<td>
<asp:Button ID=”btnSend” runat=”server” Text=”Send Result!” OnClick=”btnSend_Click” />
</td>
</tr>
<tr><td colspan=”2″>&nbsp;&nbsp;</td>
</tr>
<tr>
<td colspan=”2″>
<asp:GridView ID=”grdResultDetails” runat=”server” AutoGenerateColumns=”false”>
<HeaderStyle Font-Bold=”true” BackColor=”#ff6600″ BorderColor=”#222″
ForeColor=”White” Height=”30″ />
<Columns>
<asp:BoundField DataField=”Subjects” HeaderText=”Subjects” ItemStyle-Width=”200″
ItemStyle-HorizontalAlign=”Center” />
<asp:BoundField DataField=”Marks” HeaderText=”Marks” ItemStyle-Width=”200″
ItemStyle-HorizontalAlign=”Center” />
<asp:BoundField DataField=”Grade” HeaderText=”Grade” ItemStyle-Width=”200″
ItemStyle-HorizontalAlign=”Center” />
</Columns>
</asp:GridView>
</td>
</tr>
<tr><td colspan=”2″>&nbsp;&nbsp;</td>
</tr>
<tr>
<td colspan=”2″>
<asp:Label ID=”lblMsg” runat=”server”></asp:Label>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
Note: If you want to send gridview selected rows in mail, check out my previous tutorial on how to export gridview selected rows to word excel text pdf or send in mail here.

Function To Send Asp.net Gridview Data in Mail – [C#]

Following is the namespace required for sending emails:

using System.Net.Mail;
using System.Text;
using System.IO;

Following is the code that we need to use for sending emails:

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadGridData();
}
}

private void LoadGridData()
{
System.Data.DataTable dtSubData = new System.Data.DataTable();

//Creating grid columns
dtSubData.Columns.Add(“Subjects”);
dtSubData.Columns.Add(“Marks”);
dtSubData.Columns.Add(“Grade”);

//Adding row deails
dtSubData.Rows.Add(“Asp.net”, “70”, “B+”);
dtSubData.Rows.Add(“C#”, “80”, “A”);
dtSubData.Rows.Add(“Vb.net”, “76”, “A”);
dtSubData.Rows.Add(“HTML”, “91”, “A+”);
dtSubData.Rows.Add(“CSS”, “95”, “A+”);
dtSubData.Rows.Add(“JavaScript”, “78”, “A”);
dtSubData.Rows.Add(“jQuery”, “74”, “A”);

//Binding details to gridview
grdResultDetails.DataSource = dtSubData;
grdResultDetails.DataBind();
}

private string GridViewToHtml(GridView grdResultDetails)
{
StringBuilder objStringBuilder = new StringBuilder();
StringWriter objStringWriter = new StringWriter(objStringBuilder);
HtmlTextWriter objHtmlTextWriter = new HtmlTextWriter(objStringWriter);
grdResultDetails.RenderControl(objHtmlTextWriter);
return objStringBuilder.ToString();
}

public override void VerifyRenderingInServerForm(Control control)
{
//Required to verify that the control is rendered properly on page
}

protected void btnSend_Click(object sender, EventArgs e)
{
try
{
string Subject = “This is test mail with gridview data”,
Body = GridViewToHtml(grdResultDetails),
ToEmail = txtToEmail.Text.Trim();

string SMTPUser = “yourname@gmail.com”, SMTPPassword = “yourpassword”;

MailMessage mail = new MailMessage();
mail.From = new MailAddress(SMTPUser, “AspnetO”);
mail.To.Add(ToEmail);
mail.Subject = Subject;
mail.Body = Body;
mail.IsBodyHtml = true;
mail.Priority = MailPriority.Normal;

SmtpClient smtp = new SmtpClient();
//if you are using your smtp server, then change your host like “smtp.yourdomain.com”
smtp.Host = “smtp.gmail.com”;
//chnage your port for your host
smtp.Port = 25; //or you can also use port# 587
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;
}
}

Function To Send Asp.net Gridview Data in Mail – [Vb.net]

Following is the namespace required for sending emails:

Imports System.Net.Mail;
Imports System.Text;
Imports System.IO;

Following is the code that we need to use for sending emails:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
LoadGridData()
End If
End Sub

Private Sub LoadGridData()
Dim dtSubData As New System.Data.DataTable()

‘Creating grid columns
dtSubData.Columns.Add(“Subjects”)
dtSubData.Columns.Add(“Marks”)
dtSubData.Columns.Add(“Grade”)

‘Adding row deails
dtSubData.Rows.Add(“Asp.net”, “70”, “B+”)
dtSubData.Rows.Add(“C#”, “80”, “A”)
dtSubData.Rows.Add(“Vb.net”, “76”, “A”)
dtSubData.Rows.Add(“HTML”, “91”, “A+”)
dtSubData.Rows.Add(“CSS”, “95”, “A+”)
dtSubData.Rows.Add(“JavaScript”, “78”, “A”)
dtSubData.Rows.Add(“jQuery”, “74”, “A”)

‘Binding details to gridview
grdResultDetails.DataSource = dtSubData
grdResultDetails.DataBind()
End Sub

Private Function GridViewToHtml(ByVal grdResultDetails As GridView) As String
Dim objStringBuilder As New StringBuilder()
Dim objStringWriter As New StringWriter(objStringBuilder)
Dim objHtmlTextWriter As New HtmlTextWriter(objStringWriter)
grdResultDetails.RenderControl(objHtmlTextWriter)
Return objStringBuilder.ToString()
End Function

Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
‘Required to verify that the control is rendered properly on page
End Sub

Protected Sub btnSend_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 = txtToEmail.Text.Trim()

Dim SMTPUser As String = “yourname@gmail.com”,
SMTPPassword As String = “yourpassword”

Dim mail As New MailMessage()
mail.From = New MailAddress(SMTPUser, “AspnetO”)
mail.To.Add(ToEmail)
mail.Subject = Subject
mail.Body = Body
mail.IsBodyHtml = True
mail.Priority = MailPriority.Normal

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”
‘chnage your port for your host
smtp.Port = 25 ‘or you can also use port# 587
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, I Faced Following Error:

Control ‘grdResultDetails’ of type ‘GridView’ must be placed inside a form tag with runat=server
Server Error in ‘/’ Application.


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();
Server Error in ‘/’ Application.


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

Send asp.net gridview in smtp mail in asp.net c# vb.net

Download Example

Icon

SMTP Email Sending Examples

1 file(s) 43.07 KB
Download This Example

Signup Today And Get Latest Tutorials For Free!

Subscribe to us and get free latest tutorials notifications whenever we publish a new contents.

<

About Mayank Modi

Mayank is a web developer and designer who specializes in back-end as well as front-end development. He's a Founder & Chief Editor of AspnetO. If you'd like to connect with him, follow him on Twitter as @immayankmodi.

Leave a Reply Cancel reply

Search Your Topic



Social Connections

  • 1,438 Fans
  • 3,097 Followers
  • 51 Followers
  • 1,559 Subscribers

Get Latest Tutorials For Free



Top Posts

  • CSS3 Transition: fadeIn and fadeOut like Effects to Hide Show Elements
  • Redirect to a Specific URL on Button Click in Asp.net using JavaScript jQuery
  • Asp.net TextBox: How to Get Set TextBox Value or Text in jQuery
  • Show Alert Message Box from Code-behind in Asp.net C# Vb
  • Top 10 OOPS Concepts In C# .NET With Examples

Contribute to AspnetO

If you want to contribute your unique blog articles or tutorials (Free / Paid) to AspnetO in any languages, you're most welcome. Just send me your previous articles, and topics on which you are interested to post an tutorial. Contact us at email listed in contact us page. Selected candidates will be contacted.

Search by Tags

Ado.net Ajax appSettings Asp.net C# CheckBox CheckBoxList ConnectionStrings Control CSS CSS3 Difference Download DropDownList Export Facebook fadeIn fadeOut fadeTo fadeToggle File File Extension FileUpload Function GridView IIS Interview Questions JavaScript jQuery MVC OOP RadioButtonList RDP Repeater Send Mail Solutions Split SQL Stored Procedure TextBox Upload Validation VB Web.config Web Hosting

The Man Behind AspnetO

Mayank Modi

Hi there,

Myself Mayank Modi, a Full Stack Developer (.NET Stack) and a blogger from Surat, India.

I'm welcoming you to my blog - AspnetO, a programmers community blog where we code, that works!

I started AspnetO as a hobby and now we're growing day by day. We're now having 5000+ programmers that get benefits and learn new things about website design and development under our community blog.

Here at AspnetO, I write about Beginners to Advance level of tutorials on programming languages like Asp.net using C# and Vb.net, MVC, SQL Server, JavaScript, jQuery etc. In sort, all about .NET Framework and website development stuff and sometimes sharing tips and tricks that can help you to grow up your programming skills.

You can get more details about me and my blog at About us page.

Subscribe To Newsletter

Enter your email address to subscribe to this blog and receive notifications of new posts right to your inbox

Join 1000+ other subscribers

<

Recent Posts

  • Main Difference between SessionState and ViewState in Asp.net
  • How to Get appSettings Value from Web.config File?
  • How to Get ConnectionString from Web.config in Asp.net?
  • Difference between appSettings and connectionStrings in Web.config
  • Get Folder Files List and Export to CSV in .NET
  • Get Files List From Directory Recursively in C# Vb.net
  • Get Hash Value From Current Page URL In jQuery
  • Handle Multiple Submit Buttons in Single MVC Form

Copyright © 2014 - 2021 · All Rights Reserved.

About | Copyrights | Privacy | Terms | Contact | Advertise | Sitemap
Previous How to Send Test Mail using Gmail smtp Settings in Asp.net C# Vb.net?
Next Send HTML Webpage Content as Email Body in Asp.net C# Vb.net