ASP NET 2.0 - GridView export to EXCEL HELP

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • johnlim20088
    New Member
    • Jan 2007
    • 74

    ASP NET 2.0 - GridView export to EXCEL HELP

    Hi,

    Hi someone can help me on this?

    Currently I have a Listdata.aspx page with datagrid, I wish to export my datagrid content to excel with following code ( with button export click event):-

    But when I run the code, it raise an error
    -> Control 'ctl02_GridView 1' of type 'GridView' must be placed inside a form tag with runat=server"

    My Listdata.aspx page are place under MasterPage.aspx , which is inside Contentplace holder. how to solve this? I can't put my GridView1 in Master page, cause Listdata.aspx are inside contentplace holder of Master page. Please help

    protected void btnExport_Click (object sender, EventArgs e)
    {
    PrepareGridView ForExport(GridV iew1);
    ExportTerminati onLog();
    }

    private void PrepareGridView ForExport(Contr ol gv)
    {
    LinkButton lb = new LinkButton();
    Literal l = new Literal();

    string name = String.Empty;

    for (int i = 0; i < gv.Controls.Cou nt; i++)
    {

    if (gv.Controls[i].GetType() == typeof(LinkButt on))
    {

    l.Text = (gv.Controls[i] as LinkButton).Tex t;

    gv.Controls.Rem ove(gv.Controls[i]);

    gv.Controls.Add At(i, l);

    }

    else if (gv.Controls[i].GetType() == typeof(DropDown List))
    {

    l.Text = (gv.Controls[i] as DropDownList).S electedItem.Tex t;

    gv.Controls.Rem ove(gv.Controls[i]);

    gv.Controls.Add At(i, l);

    }

    else if (gv.Controls[i].GetType() == typeof(CheckBox ))
    {

    l.Text = (gv.Controls[i] as CheckBox).Check ed ? "True" : "False";

    gv.Controls.Rem ove(gv.Controls[i]);

    gv.Controls.Add At(i, l);

    }

    if (gv.Controls[i].HasControls())
    {
    PrepareGridView ForExport(gv.Co ntrols[i]);
    }
    }
    }


    private void ExportTerminati onLog()
    {

    string attachment = "attachment ; filename=Termin ation.xls";
    Response.ClearC ontent();
    Response.AddHea der("content-disposition", attachment);
    Response.Conten tType = "applicatio n/ms-excel";
    StringWriter sw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter( sw);
    GridView1.Rende rControl(htw);
    Response.Write( sw.ToString());
    Response.End();
    }
Working...