0

Here is my code fro converting gridview to CSV. Gridview values are not autogenerated columns,its from database as templatefield.

 try
            {
                DataTable dt1 = new DataTable();
                Response.ClearContent();
                Response.AddHeader("content-disposition", "attachment;filename=MyCsvFile.csv");
                Response.ContentType = "application/text";
                StringBuilder strBr = new StringBuilder();
                strBr.Append("\n");
                for (int j = 1; j < GridView1.Rows.Count; j++)
                {
                    strBr.AppendLine("");
                    for (int k = 0; k < GridView1.HeaderRow.Cells.Count; k++)
                    {

                        strBr.Append(GridView1.Rows[j].Cells[k].Text.Replace(",", "") + ",");

                    }
                    strBr.Append("\n");
                }
                Response.Write(strBr.ToString());
                Response.Flush();
                Response.End();
            }
            catch (Exception ex)
            {
                throw ex;
            }           

Here GridView1.Rows[j].Cells[k].Text , this "Text" contains null value. Please help...

Deenadhayalan Manoharan
  • 5,436
  • 14
  • 30
  • 50
user
  • 3
  • 2

1 Answers1

0

You need to search for the control inside the cell because columns are TemplateField.

GridView1.Rows[j].Cells[k].FindControl('ControlId').Text
Cristina Alboni
  • 1,014
  • 9
  • 15
  • Sorry..i use paging in my girdview...but the below code doesn't works for paging. please help..while converrting to CSV i get null values in notepad. GridView1.AllowPaging = false; GridView1.DataBind(); – user Apr 07 '15 at 04:30
  • If you want to export all values, you need to get them directly from the database when you create the CSV file. This code above exports only the current page in the grid. – Cristina Alboni Apr 07 '15 at 08:57
  • @ Cristina Alboni:Please tell me how to add a data table to string builder for converting it to CSV or is there any other way to convert a data table values to CSV – user Apr 08 '15 at 10:40
  • Does this post help you? http://stackoverflow.com/questions/4959722/c-sharp-datatable-to-csv – Cristina Alboni Apr 08 '15 at 10:50