Skip to content

Exporting into Excel

Azarudeen Ibn Liyakath Ali

Asked Jul 21, 2014, 4:12 AM EDT1 answer
Share
LinkedInX
When I am exporting the data from Gridview to Excel, I am getting an error.
 
C#
protected void Button1_Click(object sender, EventArgs e)
    {
        BindGrid();
    }

        private void BindGrid()
        {
        String Constr = "Data Source=WIN-A876U316VGA;integrated security=true;Initial Catalog=CUIDinfo";
        SqlConnection con = new SqlConnection(Constr);
        con.Open();
        String SelectQuery = "Select * from ParcelInfo where RequestID =" + TextBox1.Text;
        SqlCommand cmd = new SqlCommand(SelectQuery, con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        GridView1.DataSource = ds.Tables[0];
        GridView1.DataBind();
        con.Close();
    }
    protected void Button2_Click(object sender, EventArgs e)
    {

        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment;filename=Download.xls");
        Response.Charset = "";
        Response.ContentType = "application/vnd.ms-excel";
        using (StringWriter sw = new StringWriter())
        {
            HtmlTextWriter hw = new HtmlTextWriter(sw);

            //To Export all pages
            GridView1.AllowPaging = false;
            GridView1.DataBind();
            this.BindGrid();

            //GridView1.HeaderRow.BackColor = Color.White;
            foreach (TableCell cell in GridView1.HeaderRow.Cells)
            {
                cell.BackColor = GridView1.HeaderStyle.BackColor;
            }
            foreach (GridViewRow row in GridView1.Rows)
            {
                //row.BackColor = Color.White;
                foreach (TableCell cell in row.Cells)
                {
                    if (row.RowIndex % 2 == 0)
                    {
                        cell.BackColor = GridView1.AlternatingRowStyle.BackColor;
                    }
                    else
                    {
                        cell.BackColor = GridView1.RowStyle.BackColor;
                    }
                    cell.CssClass = "textmode";
                }
            }
GridView1.RenderControl(hw);  "ERROR: HTTP exception was unhandled by user code"
Code
            //style to format numbers to string
            string style = @"<style> .textmode { } </style>";
            Response.Write(style);
            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.End();
        }
    }
 
 
Could you please advise where am I going wrong??? 

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • 0
    I found it whats the error


    I forgot to add the below 

    public override void VerifyRenderingInServerForm(Control control)
        {
        }

    Now its working fine...
    0