Click here to Skip to main content
15,897,891 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hai,


I have a doubt in gridview.I get the values from the datasource and put it in a gridview with insert,update,delete operations.After that i want to convert this gridview into csv format.I tried but I got only the heading field that occured in gridview is coming.Other fields are not coming.Below I has send that code.plz rectify it.

//Default.aspx//
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head  runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1"  runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
        <br />
        <br />
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
            
            onrowcancelingedit="GridView1_RowCancelingEdit" 
            onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing" 
            onrowupdating="GridView1_RowUpdating">
            <columns>
              <asp:CommandField HeaderText="Edit-Update" ShowEditButton="True" />
                <asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True" />
                <asp:BoundField DataField="NAME" HeaderText="NAME" />
                <asp:BoundField DataField="AGE" HeaderText="AGE" />
                <asp:BoundField DataField="PLACEOFBIRTH" HeaderText="PLACEOFBIRTH" />
                <asp:CommandField HeaderText="Delete" ShowDeleteButton="True" />
               

            </columns>
        
         
        <br />
        <asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="Export to csv" />
         
    </div>
    </form>
</body>
</html>

//Default.aspx.cs//
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Text;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            binddata();
        }
    }

    private void binddata()
    {
        SqlConnection con = new SqlConnection("Data Source=MACFEESERVER;Initial Catalog=ePO_LENOVO;User ID=sa;Password=sa");
        SqlDataAdapter ada = new SqlDataAdapter("select ID,NAME,AGE,PLACEOFBIRTH from RAJ", con);
        DataTable dt = new DataTable();
        ada.Fill(dt);
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        SqlConnection con = new SqlConnection("Data Source=MACFEESERVER;Initial Catalog=ePO_LENOVO;User ID=sa;Password=sa");
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "delete from RAJ where ID=@ID";
        cmd.Parameters.Add("@ID", SqlDbType.Int).Value = Convert.ToInt32(GridView1.Rows[e.RowIndex].Cells[1].Text);
        cmd.Connection = con;
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
        binddata();
    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        binddata();
    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        binddata();
    }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        if (((LinkButton)GridView1.Rows[0].Cells[0].Controls[0]).Text == "Insert")
        {
            SqlConnection con = new SqlConnection("Data Source=MACFEESERVER;Initial Catalog=ePO_LENOVO;User ID=sa;Password=sa");
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "insert into RAJ(NAME,AGE,PLACEOFBIRTH)values(@NAME,@AGE,@PLACEOFBIRTH)";
            cmd.Parameters.Add("@NAME", SqlDbType.VarChar).Value = ((TextBox)GridView1.Rows[0].Cells[2].Controls[0]).Text;
            cmd.Parameters.Add("@AGE", SqlDbType.Int).Value = ((TextBox)GridView1.Rows[0].Cells[3].Controls[0]).Text;
            cmd.Parameters.Add("@PLACEOFBIRTH", SqlDbType.VarChar).Value = ((TextBox)GridView1.Rows[0].Cells[4].Controls[0]).Text;
            cmd.Connection = con;
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }
        else
        {
            SqlConnection con = new SqlConnection("Data Source=MACFEESERVER;Initial Catalog=ePO_LENOVO;User ID=sa;Password=sa");
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText ="update RAJ set NAME=@NAME,AGE=@AGE,PLACEOFBIRTH=@PLACEOFBIRTH where ID=@ID";
            cmd.Parameters.Add("@NAME", SqlDbType.VarChar).Value = ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
            cmd.Parameters.Add("@AGE", SqlDbType.Int).Value = ((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text;
            cmd.Parameters.Add("@PLACEOFBIRTH", SqlDbType.VarChar).Value = ((TextBox)GridView1.Rows[e.RowIndex].Cells[4].Controls[0]).Text;
            cmd.Parameters.Add("@ID",SqlDbType.Int).Value =Convert.ToInt32(GridView1.Rows[e.RowIndex].Cells[1].Text);
            cmd.Connection = con;
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();

        }
        GridView1.EditIndex = -1;
        binddata();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection("Data Source=MACFEESERVER;Initial Catalog=ePO_LENOVO;User ID=sa;Password=sa");
        SqlDataAdapter ada = new SqlDataAdapter("select ID,NAME,AGE,PLACEOFBIRTH from RAJ", con);
        DataTable dt = new DataTable();
        ada.Fill(dt);
        DataRow dr = dt.NewRow();
        dt.Rows.InsertAt(dr, 0);
        GridView1.EditIndex = 0;
        GridView1.DataSource = dt;
        GridView1.DataBind();
        ((LinkButton)GridView1.Rows[0].Cells[0].Controls[0]).Text = "Insert";
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.csv");
        Response.Charset = "";
        Response.ContentType = "application/text";





        GridView1.AllowPaging = false;
        GridView1.DataBind();

        StringBuilder sb = new StringBuilder();
        for (int k = 0; k < GridView1.Columns.Count; k++)
        {
            //add separator
            sb.Append(GridView1.Columns[k].HeaderText + ',');
        }
        //append new line
        sb.Append("\r\n");
        for (int i = 0; i < GridView1.Rows.Count; i++)
        {
            for (int k = 0; k < GridView1.Columns.Count; k++)
            {
                //add separator
                sb.Append(GridView1.Rows[i].Cells[k].Text + ',');
            }
            //append new line
            sb.Append("\r\n");
        }
        Response.Output.Write(sb.ToString());
        Response.Flush();
        Response.End();

    }
}
Posted

You need to export data to a csv file. See here[^].
 
Share this answer
 
Comments
Albin Abel 15-Mar-11 1:17am    
Abhinav, I haven't tested the solution given by Soni Uma, but by seeing its simplicity I just suggested. I think you also answered it there. Anyway thanks for your vote. My vote for, may be your method is the working one.
This topic is discussed here in code project. I hope there is same method for CSV as well.

This method seems to be simple (Answer by Soni Uma). I haven't tested, so I am not it works well.

Export Gridview to Excel in ASP.NET[^]
 
Share this answer
 
Comments
Abhinav S 15-Mar-11 1:04am    
Fair enough. 5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900