Saturday, 11 May 2013

How to Export gridview to excel within an UpdatePanel in asp.net using c#


How to Export gridview to excel within an UpdatePanel in asp.net using c#


In this example i'm explaining how to Create Or Export GridView to Excel In Asp.Net  using C#  Place one button on the page for exporting data to ms excel file

Here I am using Northwind Database to populate 


CategoryIDCategoryNameDescription
1BeveragesSoft drinks, coffees, teas, beers, and ales
2CondimentsSweet and savory sauces, relishes, spreads, and seasonings
3ConfectionsDesserts, candies, and sweet breads
4Dairy ProductsCheeses
5Grains/CerealsBreads, crackers, pasta, and cereal
6Meat/PoultryPrepared meats
7ProduceDried fruit and bean curd
8SeafoodSeaweed and fish
HTML Code


<%@ 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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <asp:GridView ID="grvGridtoExcelFile" runat="server" CellPadding="4" PageSize="4" Width="628px" > 
            <RowStyle BackColor="AliceBlue" />
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
        <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <EditRowStyle BackColor="#2461BF" />
        <AlternatingRowStyle BackColor="White" />          
            </asp:GridView>
            
            <asp:Button ID="btnExport" runat="server" Text="Export Grid to ExcelFile" OnClick="btnExport_click" />
        </ContentTemplate>
        <Triggers>
        <asp:PostBackTrigger ControlID="btnExport" />
        </Triggers>

    </asp:UpdatePanel>
    

    </div>
    
    </form>
</body>
</html>


Code Behind Code  :


using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;
public partial class _Default : System.Web.UI.Page 
{

    SqlConnection con = null;
    SqlDataAdapter adapter = null;

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

    private void BindGridData()
    {
        con = new SqlConnection(@"Data Source=ram-pc\sqlexpress;Initial Catalog=Northwind;Integrated Security=True");
        adapter = new SqlDataAdapter("select * from Categories", con);
        DataSet ds = new DataSet();
        adapter.Fill(ds, "Categories");
        grvGridtoExcelFile.DataSource = ds.Tables["Categories"];
        grvGridtoExcelFile.DataBind();
    }

    protected void btnExport_click(object sender, EventArgs e)
    {
        Response.Clear();
        Response.AddHeader("content-disposition", "attachment;filename=Suppliers.xls");
        Response.Charset = "";
        Response.ContentType = "application/vnd.xls";
        System.IO.StringWriter stringWrite = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
        grvGridtoExcelFile.RenderControl(htmlWrite);
        Response.Write(stringWrite.ToString());
        Response.End();

    }


But when we try to execute this code on we get this httpexception error.

Control 'grvGridtoExcelFile' of type 'GridView' must be placed inside a form tag with runat=server.

httpexception error

to get past this error we can write this method in code behind.



   public override void VerifyRenderingInServerForm(Control control)
    {
    }


















1 comment: