In my previous tutorials, I’d explained how to export gridview data to word excel text pdf in .net, get gridview selected row hiddenfield values, print gridview data on print button click, and other more cracking tutorials on GridView, Asp.net, JavaScript, jQuery here.
Now here in this tutorial, I’ll explain how to export gridview selected row data with gridview’s exact CSS style and format to word, excel, pdf (using itextsharp.dll), and text file in asp.net using c# as well as vb.net with example code. Also explained how to send selected gridview row data in the email body.
To explain further about how to export gridview selected row data in asp.net, we need to create database table to read data and bind retrieved resultset to gridview, so simply execute the following script to SQL query editor to create database table and then add few records manually or download complete example code with script at the end of the page.
Here is the script to create “œSubjectDetails” table:
(
[SubjectId] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
[SubjectName] [nvarchar](100) NULL,
[Marks] [int] NULL,
[Grade] [nvarchar](50) NULL
)
I guess you all know about how to bind gridview. So I’m skipping that point and come to the subject to export gridview data to word, excel, csv, pdf and text file. Following is the HTML Markup that contains asp.net buttons and gridview, simply copy and paste to your .aspx page:
Export GridView Selected Row Data In Asp.net – [.aspx]
<head id=”Head1″ runat=”server”>
<title>Export gridview selected row data to Word, Excel, CSV, Pdf File Examples</title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<table>
<tr>
<td colspan=”3″>
<h4>Export gridview selected row data to Word, Excel, CSV, Pdf File in Asp.net</h4>
** By default it’ll export all data
</td>
</tr>
<tr><td colspan=”3″> </td></tr>
<tr>
<td colspan=”3″>
<asp:Button ID=”btnExportToWord” runat=”server” Text=”ExportToWord”
OnClick=”btnExportToWord_Click” />
<asp:Button ID=”btnExportToExcel” runat=”server” Text=”ExportToExcel”
OnClick=”btnExportToExcel_Click” />
<asp:Button ID=”btnExportToCSV” runat=”server” Text=”ExportToCSV”
OnClick=”btnExportToCSV_Click” />
<asp:Button ID=”btnExportToText” runat=”server” Text=”ExportToText”
OnClick=”btnExportToText_Click” />
<asp:Button ID=”btnExportToPdf” runat=”server” Text=”ExportToPdf”
OnClick=”btnExportToPdf_Click” />
<asp:Button ID=”btnSendMail” runat=”server” Text=”Send Mail”
OnClick=”btnSendMail_Click” />
</td>
</tr>
<tr>
<td colspan=”3″>
<asp:GridView ID=”grdResultDetails” runat=”server” AutoGenerateColumns=”false”
DataKeyNames=”SubjectId” AllowPaging=”true” PageSize=”5″
OnPageIndexChanging=”grdResultDetails_PageIndexChanging”>
<HeaderStyle BackColor=”#9a9a9a” ForeColor=”White” Font-Bold=”true” Height=”30″ />
<PagerStyle HorizontalAlign=”Center” />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID=”chkSelectRow” runat=”server” />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField=”SubjectId” HeaderText=”SubjectID”
ItemStyle-Width=”100″ ItemStyle-HorizontalAlign=”Center” />
<asp:BoundField DataField=”SubjectName” HeaderText=”SubjectName”
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>
</table>
<asp:Label ID=”lblMsg” runat=”server” />
</div>
</form>
</body>
</html>
After copying HTML Markup, now it’s time to add required .dll and namespace references to the code-behind file. To add a reference to your project Right Click on References > Add New Reference > Browse to itextsharp.dll > OK.
Note: We need itextsharp.dll to export data to Pdf file (only requires for pdf export, if you don’t want export to pdf functionality, then simply ignore itextsharp.dll and remove a reference from the sample project).I already added itextsharp.dll in my sample code. If you want to get more details about itextsharp.dll, visit itextsharp official site here.
After adding the reference, choose a required language (C# or Vb.net), and then copy paste the following code to your code-behind file.
Export GridView to Excel, Word, Text, Pdf In C#
First add the following namespaces to your .cs page:
using System.IO;
using System.Text;
using iTextSharp;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
using System.Data.SqlClient;
using System.Collections;
using System.Net.Mail;
Then add the following code snippet to your code-behind file which helps you to keep selected rows on PageIndexChanging event and maintain the state of the selected rows to export that rows with paging:
protected void grdResultDetails_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
//Save checked rows before page change
SaveCheckedStates();
grdResultDetails.PageIndex = e.NewPageIndex;
LoadGridData();
//Populate cheked items with its checked status
PopulateCheckedStates();
}//Save the state of row checkboxes
private void SaveCheckedStates()
{
ArrayList objSubjectAL = new ArrayList();
int rowIndex = -1;
foreach (GridViewRow row in grdResultDetails.Rows)
{
rowIndex = Convert.ToInt32(grdResultDetails.DataKeys[row.RowIndex].Value);
bool isSelected = ((CheckBox)row.FindControl(“chkSelectRow”)).Checked;
if (ViewState[“SELECTED_ROWS”] != null)
{
objSubjectAL = (ArrayList)ViewState[“SELECTED_ROWS”];
}
if (isSelected)
{
if (!objSubjectAL.Contains(rowIndex))
{
objSubjectAL.Add(rowIndex);
}
}
else
{
objSubjectAL.Remove(rowIndex);
}
}
if (objSubjectAL != null && objSubjectAL.Count > 0)
{
ViewState[“SELECTED_ROWS”] = objSubjectAL;
}
}//Populate the saved checked checkbox status
private void PopulateCheckedStates()
{
ArrayList objSubjectAL = (ArrayList)ViewState[“SELECTED_ROWS”];
if (objSubjectAL != null && objSubjectAL.Count > 0)
{
foreach (GridViewRow row in grdResultDetails.Rows)
{
int rowIndex = Convert.ToInt32(grdResultDetails.DataKeys[row.RowIndex].Value);
if (objSubjectAL.Contains(rowIndex))
{
CheckBox chkSelectRow = (CheckBox)row.FindControl(“chkSelectRow”);
chkSelectRow.Checked = true;
}
}
}
}
Now here are the common functions to export gridview data to word, excel, CSV, pdf, text files:
private void ExportFile(string fileName, string contentType)
{
SaveCheckedStates();
//disable paging to export all pages data and make sure to bind griddata before begin
grdResultDetails.AllowPaging = false;
LoadGridData();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader(“content-disposition”, string.Format(“attachment; filename={0}”, fileName));
Response.ContentType = contentType;
StringWriter objSW = new StringWriter();
HtmlTextWriter objHW = new HtmlTextWriter(objSW);
grdResultDetails.HeaderRow.Style.Add(“background-color”, “#fff”);
grdResultDetails.Columns[0].Visible = false;
for (int i = 0; i < grdResultDetails.HeaderRow.Cells.Count; i++)
{
grdResultDetails.HeaderRow.Cells[i].Style.Add(“background-color”, “#9a9a9a”);
}
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);
Response.Write(objSW);
Response.End();
}//2nd Method: To Export to CSV, Text file
private void ExportTextBasedFile(string fileName, string contentType)
{
SaveCheckedStates();
//disable paging to export all data and make sure to bind griddata before begin
grdResultDetails.AllowPaging = false;
LoadGridData();Response.ClearContent();
Response.AddHeader(“content-disposition”, string.Format(“attachment; filename={0}”, fileName));
Response.ContentType = contentType;
StringBuilder objSB = new StringBuilder();
grdResultDetails.Columns[0].Visible = false;
for (int i = 1; i < grdResultDetails.Columns.Count; i++)
{
objSB.Append(grdResultDetails.Columns[i].HeaderText + ‘,’);
}
objSB.Append(“\n”);
ArrayList objSelectedRowsAL = (ArrayList)ViewState[“SELECTED_ROWS”];
for (int j = 0; j < grdResultDetails.Rows.Count; j++)
{
bool isRowSelected = true;
if (ViewState[“SELECTED_ROWS”] != null)
{
GridViewRow row = grdResultDetails.Rows[j];
int rowIndex = Convert.ToInt32(grdResultDetails.DataKeys[row.RowIndex].Value);
isRowSelected = objSelectedRowsAL.Contains(rowIndex);
}
if (isRowSelected)
{
//if row is selected then add row to csv file, else ignore row
for (int k = 1; k < grdResultDetails.Columns.Count; k++)
{
objSB.Append(grdResultDetails.Rows[j].Cells[k].Text + ‘,’);
}
objSB.Append(“\n”);
}
}
Response.Write(objSB.ToString());
Response.End();
}
And call each function on specific button event as follows:
protected void btnExportToWord_Click(object sender, EventArgs e)
{
string fileName = “ExportToWord_” + DateTime.Now.ToShortDateString() + “.doc”,
contentType = “application/ms-word”;//call 1st export method with filename and contenttype
ExportFile(fileName, contentType);
}//Method for Export to Excel
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
string fileName = “ExportToExcel_” + DateTime.Now.ToShortDateString() + “.xls”,
contentType = “application/vnd.ms-excel”;
//call 1st export method with filename and contenttype
ExportFile(fileName, contentType);
}
/* Method for Export to CSV
* Note: CSV file is a text representation so we can’t style .csv document*/
protected void btnExportToCSV_Click(object sender, EventArgs e)
{
string fileName = “ExportToCsv_” + DateTime.Now.ToShortDateString() + “.csv”,
contentType = “application/text”;
//call 2nd export method with filename and contenttype
ExportTextBasedFile(fileName, contentType);
}
/* Method for Export to Text
* Note: TEXT file is a text representation so we can’t style .txt document*/
protected void btnExportToText_Click(object sender, EventArgs e)
{
string fileName = “ExportToText_” + DateTime.Now.ToShortDateString() + “.txt”,
contentType = “application/text”;
//call 2nd export method with filename and contenttype
ExportTextBasedFile(fileName, contentType);
}
Following is the method to export Gridview to PDF File:
{
SaveCheckedStates();
//disable paging to export all data and make sure to bind griddata before begin
grdResultDetails.AllowPaging = false;
LoadGridData();string fileName = “ExportToPdf_” + DateTime.Now.ToShortDateString();
Response.ContentType = “application/pdf”;
Response.AddHeader(“content-disposition”, string.Format(“attachment; filename={0}”,
fileName + “.pdf”));
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter objSW = new StringWriter();
HtmlTextWriter objTW = new HtmlTextWriter(objSW);
grdResultDetails.Columns[0].Visible = false;
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(objTW);
StringReader objSR = new StringReader(objSW.ToString());
Document objPDF = new Document(PageSize.A4, 100f, 100f, 100f, 100f);
HTMLWorker objHW = new HTMLWorker(objPDF);
PdfWriter.GetInstance(objPDF, Response.OutputStream);
objPDF.Open();
objHW.Parse(objSR);
objPDF.Close();
Response.Write(objPDF);
Response.End();
}
Export GridView Data to Excel, Word, Text, Pdf In Vb.net
First add the following namespaces to your .vb page:
Imports iTextSharp.text
Imports iTextSharp.text.html.simpleparser
Imports iTextSharp.text.pdf
Imports System.Data.SqlClient
Imports System.Net.Mail
Then add the following code snippet to your code-behind file which helps you to keep selected rows on PageIndexChanging event and maintain the state of the selected rows to export that rows with paging:
Protected Sub grdResultDetails_PageIndexChanging(ByVal sender As Object,
ByVal e As GridViewPageEventArgs)
‘Save checked rows before page change
SaveCheckedStates()
grdResultDetails.PageIndex = e.NewPageIndex
LoadGridData()
‘Populate cheked items with its checked status
PopulateCheckedStates()
End Sub‘Save the state of row checkboxes
Private Sub SaveCheckedStates()
Dim objSubjectAL As New ArrayList()
Dim rowIndex As Integer = -1
For Each row As GridViewRow In grdResultDetails.Rows
rowIndex = Convert.ToInt32(grdResultDetails.DataKeys(row.RowIndex).Value)
Dim isSelected As Boolean = CType(row.FindControl(“chkSelectRow”), CheckBox).Checked
If ViewState(“SELECTED_ROWS”) IsNot Nothing Then
objSubjectAL = CType(ViewState(“SELECTED_ROWS”), ArrayList)
End If
If isSelected Then
If Not objSubjectAL.Contains(rowIndex) Then
objSubjectAL.Add(rowIndex)
End If
Else
objSubjectAL.Remove(rowIndex)
End If
Next row
If objSubjectAL IsNot Nothing AndAlso objSubjectAL.Count > 0 Then
ViewState(“SELECTED_ROWS”) = objSubjectAL
End If
End Sub‘Populate the saved checked checkbox status
Private Sub PopulateCheckedStates()
Dim objSubjectAL As ArrayList = CType(ViewState(“SELECTED_ROWS”), ArrayList)
If objSubjectAL IsNot Nothing AndAlso objSubjectAL.Count > 0 Then
For Each row As GridViewRow In grdResultDetails.Rows
Dim rowIndex As Integer = Convert.ToInt32(grdResultDetails.DataKeys(row.RowIndex).Value)
If objSubjectAL.Contains(rowIndex) Then
Dim chkSelectRow As CheckBox = CType(row.FindControl(“chkSelectRow”), CheckBox)
chkSelectRow.Checked = True
End If
Next row
End If
End Sub
Now here are the common functions to export gridview data to word, excel, CSV, pdf, text files:
1st Method: To Export to Word, Excel file
SaveCheckedStates()
‘disable paging to export all pages data and make sure to bind griddata before begin
grdResultDetails.AllowPaging = False
LoadGridData()
Response.ClearContent()
Response.Buffer = True
Response.AddHeader(“content-disposition”, String.Format(“attachment; filename={0}”, fileName))
Response.ContentType = contentType
Dim objSW As New StringWriter()
Dim objHW As New HtmlTextWriter(objSW)
grdResultDetails.HeaderRow.Style.Add(“background-color”, “#fff”)
grdResultDetails.Columns(0).Visible = False
For i As Integer = 0 To grdResultDetails.HeaderRow.Cells.Count – 1
grdResultDetails.HeaderRow.Cells(i).Style.Add(“background-color”, “#9a9a9a”)
Next i
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)
Response.Write(objSW)
Response.End()
End Sub
2nd Method: To export gridview to CSV, Text file
Private Sub ExportTextBasedFile(ByVal fileName As String, ByVal contentType As String)
SaveCheckedStates()
‘disable paging to export all data and make sure to bind griddata before begin
grdResultDetails.AllowPaging = False
LoadGridData()
Response.ClearContent()
Response.AddHeader(“content-disposition”, String.Format(“attachment; filename={0}”, fileName))
Response.ContentType = contentType
Dim objSB As New StringBuilder()
grdResultDetails.Columns(0).Visible = False
For i As Integer = 1 To grdResultDetails.Columns.Count – 1
objSB.Append(grdResultDetails.Columns(i).HeaderText)
objSB.Append(“,”c)
Next i
objSB.Append(ControlChars.Lf)
Dim objSelectedRowsAL As ArrayList = CType(ViewState(“SELECTED_ROWS”), ArrayList)
For j As Integer = 0 To grdResultDetails.Rows.Count – 1
Dim isRowSelected As Boolean = True
If ViewState(“SELECTED_ROWS”) IsNot Nothing Then
Dim row As GridViewRow = grdResultDetails.Rows(j)
Dim rowIndex As Integer = Convert.ToInt32(grdResultDetails.DataKeys(row.RowIndex).Value)
isRowSelected = objSelectedRowsAL.Contains(rowIndex)
End If
If isRowSelected Then
‘if row is selected then add row to csv file, else ignore row
For k As Integer = 1 To grdResultDetails.Columns.Count – 1
objSB.Append(grdResultDetails.Rows(j).Cells(k).Text)
objSB.Append(“,”c)
Next k
objSB.Append(ControlChars.Lf)
End If
Next j
Response.Write(objSB.ToString())
Response.End()
End Sub
And call each function on a specific button event as follows:
Protected Sub btnExportToWord_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim fileName As String = “ExportToWord_” & Date.Now.ToShortDateString() & “.doc”,
contentType As String = “application/ms-word”‘call 1st export method with filename and content type
ExportFile(fileName, contentType)
End Sub
Method for export gridview data to excel
Protected Sub btnExportToExcel_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim fileName As String = “ExportToExcel_” & Date.Now.ToShortDateString() & “.xls”,
contentType As String = “application/vnd.ms-excel”
‘call 1st export method with filename and contenttype
ExportFile(fileName, contentType)
End Sub
Method for export gridview to csv C#
‘Note: CSV file is a text representation so we can’t style .csv document
Protected Sub btnExportToCSV_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim fileName As String = “ExportToCsv_” & Date.Now.ToShortDateString() & “.csv”,
contentType As String = “application/text”
‘call 2nd export method with filename and contenttype
ExportTextBasedFile(fileName, contentType)
End Sub
‘Method for Export to Text
‘Note: TEXT file is a text representation so we can’t style .txt document
Protected Sub btnExportToText_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim fileName As String = “ExportToText_” & Date.Now.ToShortDateString() & “.txt”,
contentType As String = “application/text”
‘call 2nd export method with filename and contenttype
ExportTextBasedFile(fileName, contentType)
End Sub
Following is the method to export gridview to pdf in asp.net:
Protected Sub btnExportToPdf_Click(ByVal sender As Object, ByVal e As EventArgs)
SaveCheckedStates()
‘disable paging to export all data and make sure to bind griddata before begin
grdResultDetails.AllowPaging = False
LoadGridData()Dim fileName As String = “ExportToPdf_” & Date.Now.ToShortDateString()
Response.ContentType = “application/pdf”
Response.AddHeader(“content-disposition”, String.Format(“attachment; filename={0}”,
fileName & “.pdf”))
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Dim objSW As New StringWriter()
Dim objTW As New HtmlTextWriter(objSW)
grdResultDetails.Columns(0).Visible = False
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(objTW)
Dim objSR As New StringReader(objSW.ToString())
Dim objPDF As New Document(PageSize.A4, 100.0F, 100.0F, 100.0F, 100.0F)
Dim objHW As New HTMLWorker(objPDF)
PdfWriter.GetInstance(objPDF, Response.OutputStream)
objPDF.Open()
objHW.Parse(objSR)
objPDF.Close()
Response.Write(objPDF)
Response.End()
End Sub
Function To Send GridView Selected Row Data As Email Body
I guess you all know about how to send mail using smtp in asp.net. Also check out my previous tutorial on how to send gridview data in mail using asp.net c# or vb.net. Following function allows you to send only gridview selected rows in mail.
If you are using C# as code-behind, use the following code:
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”;
MailMessage mail = new MailMessage();
//set the sender address of the mail message
mail.From = new System.Net.Mail.MailAddress(SMTPUser, “AspnetO”);
mail.To.Add(ToEmail);
mail.Subject = Subject;
mail.Body = Body;
mail.IsBodyHtml = true;
mail.Priority = System.Net.Mail.MailPriority.Normal;
SmtpClient smtp = new SmtpClient();
//chnage your host, port number
smtp.Host = “smtp.gmail.com”;
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;
}
}//Method To Convert Gridview To HTML formatted String
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();
}
If you are using Vb.net as code-behind, use following code:
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”Dim mail As New MailMessage()
Set the sender address of the mail message
mail.From = New System.Net.Mail.MailAddress(SMTPUser, “AspnetO”)
mail.To.Add(ToEmail)
mail.Subject = Subject
mail.Body = Body
mail.IsBodyHtml = True
mail.Priority = System.Net.Mail.MailPriority.Normal
Dim smtp As New SmtpClient()
‘chnage your host, port number
smtp.Host = “smtp.gmail.com”
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
Method To Convert Gridview To HTML formatted String
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
During Development, I Faced Following Errors:
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();.
Hi. I used your code for export now i need to this excel content as body for email purpose, could you please update it. i want thank you for the wonderful code used above.. its working well….
Thanks. I guess, you are looking for this https://www.aspneto.com/send-asp-net-gridview-in-smtp-mail-in-asp-net-c-vb-net.html
Hi Mayank, Yes you are right.. but in the link code you have used datatable.. its ok. but i need only selected to export using checks.. in this content really excellent for only selected export.. so this same to be works in email.. hope you understood my query.
Post is updated, Check at the end of this post!