I have this code which export data from GridView to csv. It works with other sites but not on this current one I’ve been developing.
The GridView is binded with DataTable in code behind. Following is the event that binds the fetch and bind the data to GridView.
private void bindGridView()
{
//Fetching data from DB goes here
myTable.Columns.Add("type", typeof(int));
myTable.Columns.Add("rate", typeof(int));
foreach (DataRow rows in myTable.Rows)
{
if (rows["dst"].ToString() == "1875")
{
rows["type"] = 1;
rows["rate"] = 500;
rows.AcceptChanges();
}
else if (rows["dst"].ToString() == "1876")
{
rows["type"] = 0;
rows["rate"] = 30;
rows.AcceptChanges();
}
}
gridViewData.DataSource = myTable;
gridViewData.AllowPaging = true;
gridViewData.PageSize = 10;
gridViewData.DataBind();
}
Following is the button click event to export data from GridView
protected void btnExportCDR_Click(object sender, EventArgs e)
{
if (gridViewData.Rows.Count == 0)
{
lblStatus.Text = "Data is empty. Can not export CDR. Please check your filtering dates.";
}
else
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=CDRMMCC_" + System.DateTime.Now.ToShortDateString() + ".csv");
Response.Charset = "";
Response.ContentType = "application/text";
bindGridView();
gridViewData.AllowPaging = false;
StringBuilder sb = new StringBuilder();
//I did a trace here, gridViewData.Columns.Count is 0. That's why it got skipped, I think.
for (int k = 0; k < gridViewData.Columns.Count; k++)
{
sb.Append(gridViewData.Columns[k].HeaderText + ",");
}
sb.Append("\r\n");
for (int i = 0; i < gridViewData.Rows.Count; i++)
{
for (int k = 0; k < gridViewData.Columns.Count; k++)
{
sb.Append(gridViewData.Rows[i].Cells[k].Text + ",");
}
sb.Append("\r\n");
}
Response.Output.Write(sb.ToString());
Response.Flush();
Response.End();
}
}
Please advice.
If you use the
AutoGenerateColumnsproperty of theGridViewset totruetheColumnscollection will be empty. The MSDN documentation for this property says:“Automatically generated bound column fields are not added to the Columns collection”.
This is the reason your
Columnscollection is empty. As Henk Holterman pointed out use yourDataTabledirectly to generate your CSV file.An alternative approach would be to set the
AutoGenerateColumnsproperty tofalseand define the Columns explicitly.