* IBM to offer mobile security as a service IBM will start delivering mobile security-as-a-service (MaaS) through its own cloud infrastructure in India, a move that is expected to better address in-country data requirements... IBM Spectrum Computing: IBM has enlarged its portfolio of software-defined infrastructure solutions with cognitive features for workload management.  * LiFi internet technology has been introduced, the new type of wireless internet connection that gives 100 times faster than traditional WiFi -- Invented by Professor Harald Haas from the University of Edinburgh. * Sci. Rachid Yazami has developed a smart chip that charges smartphones in less than 10 minutes. BenQ has launched BlueCore projector - Consumer electronics major BenQ has launched its first BlueCore laser light source projector. For those unaware, devices with BlueCore laser technology have a high contrast output of 80000:1 with an extended lamp life and efficiency. *** 
  Jan 25 2015 9:40AM     Michael Ryan
  2 Comments    7922 Views  
Here Michael Ryan provided a short tutorial with example, how to Export Gridview records to CSV in ASP.Net C#/VB
For binding the gridview, First have to create a table in Microsoft SQL Server Database as shown below.
Creating a table
When creating a table make Identity Specification as true for column 'ID'.

Set the table name as shown below.
Adding a GridView to the Page
Firstly you need to add a GridView control to the ASP.Net Web Page from the Visual Studio ToolBox as shown below.

Below is the sample HTML code,

<html xmlns="">
<head runat="server">
    <form id="form1" runat="server">
            Employee Details</h2>        
        <br >
        <asp:GridView ID="GridEmployee" runat="server" CellPadding="5" Style="background-color: rgb(241, 241, 241); width: 50%;">           
    <br >
    <br >

    <asp:Button ID="btnExportToCSV" runat="server" Text="Export to CSV" OnClick="btnExportToCSV_Click" 
     Style="color: Black; font-size: 12px; font-weight: bold; height: 30px;"/>


Below is the sample Web.config file Code,

    <add name="ConnectionString" connectionString="server=SERVER-NAME;database=DATABASE-NAME;uid=USER-ID;password=PASSWORD;"/>   

You will need to import the following namespace.

using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.Text;


Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Text

Export Gridview records to CSV
Below is the sample code to Export Gridview records to CSV in ASP.Net C#/VB.

        protected void Page_Load(object sender, EventArgs e)
            if (!IsPostBack)
                GridEmployee.DataSource = GetData("SELECT EmployeeName, EmployeeAge, EmployeeDesc, EmployeeExperience FROM Employee");

        private DataSet GetData(string query)
            string conString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            SqlCommand cmd = new SqlCommand(query);
            using (SqlConnection con = new SqlConnection(conString))
                using (SqlDataAdapter sda = new SqlDataAdapter())
                    cmd.Connection = con;
                    sda.SelectCommand = cmd;
                    using (DataSet ds = new DataSet())
                        return ds;

        protected void btnExportToCSV_Click(object sender, EventArgs e)

        private void ExportGridToCSV()
            Response.Buffer = true;
            Response.Charset = "";
            Response.ContentType = "application/text";
            GridEmployee.AllowPaging = false;

            StringBuilder columnbind = new StringBuilder();
            for (int k = 0; k < GridEmployee.Columns.Count; k++)

                columnbind.Append(GridEmployee.Columns[k].HeaderText + ',');

            for (int i = 0; i < GridEmployee.Rows.Count; i++)
                for (int k = 0; k < GridEmployee.Columns.Count; k++)

                    columnbind.Append(GridEmployee.Rows[i].Cells[k].Text + ',');




    Protected Sub Page_Load(ByVal sender As ObjectByVal e As EventArgs)

        If Not IsPostBack Then
            GridEmployee.DataSource = GetData("SELECT EmployeeName, EmployeeAge, EmployeeDesc, EmployeeExperience FROM Employee")
        End If

    End Sub
    Private Function GetData(ByVal query As StringAs DataSet

        Dim conString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
        Dim cmd  SqlCommand = New (query)
        Dim con  SqlConnection = New (conString)
        Dim sda  SqlDataAdapter = New SqlDataAdapter()
        cmd.Connection = con
        sda.SelectCommand = cmd
        Dim ds  DataSet = New Dataset()
        Return ds

    End Function
    Protected Sub btnExportToCSV_Click(ByVal sender As ObjectByVal e As EventArgs)


    End Sub
    Private Sub ExportGridToCSV()

        Response.Buffer = true
        Response.Charset = ""
        Response.ContentType = "application/text"
        GridEmployee.AllowPaging = false
        Dim columnbind  StringBuilder = New StringBuilder()
        Dim k As Integer = 0
        Do While (k < GridEmployee.Columns.Count)
            columnbind.Append((GridEmployee.Columns(k).HeaderText + Microsoft.VisualBasic.ChrW(44)))
            k = (k + 1)
        columnbind.Append(""& vbCrLf)
        Dim i As Integer = 0
        Do While (i < GridEmployee.Rows.Count)
            Dim k As Integer = 0
            Do While (k < GridEmployee.Columns.Count)
                columnbind.Append((GridEmployee.Rows(i).Cells(k).Text + Microsoft.VisualBasic.ChrW(44)))
                k = (k + 1)
            columnbind.Append(""& vbCrLf)
            i = (i + 1)

    End Sub

I hope this page will helps to delete rows in Gridview using Checkbox in ASP.Net application. Thanks.

Sep 5 2015 4:04AM
The problem, I am having is that after the export to csv, the page no longer reacts to another button click and needs to be refreshed.
Feb 20 2019 10:46PM
What can I do to throw the file without the header from the second line thanks

Recent Posts
Create Amazon ElasticCache Using Memcached in CSharp
Oct 29 2018 12:09PM Posted By Amose
Get Google Map Lat Lng (Geo Point) By Pincode in C#
Oct 28 2018 12:09PM Posted By Pranav
Google URL Shortener in C#
Oct 20 2018 12:09PM Posted By Sanjay
Bind Gridview from CSV file in Asp.Net C#
Oct 5 2018 12:09PM Posted By Michael
Call WebService method from jQuery in every 1 minute
Sep 26 2018 12:09PM Posted By John
Gridview custom CSS in ASP.Net
Sep 14 2018 12:09PM Posted By Micheal Ryan
Read excel file and bind to Gridview in C#
Sep 10 2018 12:09PM Posted By Micheal
Follow us on Facebook
Follow us on Google +
Recent post in your Email inbox.
Enter your email address: