Reputation: 2207
I having issues exporting a GridView to Excel for some reason. I have two buttons, one is the Search which handles the search once the user has provided the required information. The other button is the Export which basically handles the export of the gridview to excel.
My problem is that when an user clicks on the search button and then they want to export the data to excel they need to click on the Export button. Everything is good until this point, when the excel file is view, no data is exported. Here is my code for both buttons:
Any help will be appreciate it, thanks.
protected void search(object sender, EventArgs e)
{
odbc.Open();
ds = new DataSet();
cmd = new OdbcCommand("SELECT XHLBCD AS LOCATION, XHLCST AS STATUS, XHEXUN AS EXCESS, XHSHUN AS SHORT, XHCNTD AS DATE_COUNTED FROM " +
"WM242BASD.XHCTRL00 WHERE XHCNTD BETWEEN '" + fromdate.Text + "' AND '" + todate.Text + "'", odbc);
cmd.CommandType = CommandType.Text;
cmd.Connection = odbc;
oda = new OdbcDataAdapter(cmd);
oda.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
odbc.Close();
}
protected void export_OnClick(object sender, EventArgs e)
{
// Let's hide all unwanted stuffing
GridView1.AllowPaging = false;
GridView1.AllowSorting = false;
// Let's bind data to GridView
BindGrid();
//Change the color back to white
GridView1.HeaderRow.Style.Add("background-color", "#ffffff");
//Apply color to the header
GridView1.HeaderRow.Cells[0].Style.Add("background-color", "#e0e0e0");
GridView1.HeaderRow.Cells[1].Style.Add("background-color", "#e0e0e0");
GridView1.HeaderRow.Cells[2].Style.Add("background-color", "#e0e0e0");
GridView1.HeaderRow.Cells[3].Style.Add("background-color", "#e0e0e0");
GridView1.HeaderRow.Cells[4].Style.Add("background-color", "#e0e0e0");
// Let's output the GridView
Response.Clear();
Response.ContentType = "application/vnd.xls";
Response.AddHeader("content-disposition", "attachment;filename=" + reportid + ".xls");
StringWriter swriter = new StringWriter();
HtmlTextWriter hwriter = new HtmlTextWriter(swriter);
GridView1.RenderControl(hwriter);
Response.Write(swriter.ToString());
Response.End();
}
private void BindGrid()
{
GridView1.DataBind();
}
Upvotes: 1
Views: 2468
Reputation: 21881
You need to give the grid a datasource in both instances, you get no data from your export because the gridview hasn't got a datasource at that point.
Move the code from the search method into your databaind method and call the method from both event handlers.
Also use SQL parameters you code is wide open for SQL injection attacks.
Upvotes: 2