In one of my previous articles you saw how to export Datagrid to text files Datagrid Export to Excel, Text and Word Files. In this article we will see how we can export a GridView control to text files.

 

Introduction:

In one of my previous articles you saw how to export Datagrid to text files Datagrid Export to Excel, Text and Word Files. In this article we will see how we can export a GridView control to text files.  

Exporting GridView to text file:

Exporting GridView to text file is very similar to exporting Datagrid to text file. Let's see the code below:

StringBuilder str = new StringBuilder();

for (int i = 0; i < GridView1.Rows.Count; i++)

{

for(int j=0;j<GridView1.Rows[i].Cells.Count; j++)

{

str.Append(GridView1.Rows[i].Cells[j].Text);

}

// Add a line break

str.Append("<BR>");

}

All I am doing in the code above is iterating through the Rows and Cells and appending the data into the StringBuilder object. Now let's see how we can export it to text file. 

// Output the text file to the stream

Response.Clear();

Response.AddHeader("content-disposition", "attachment;filename=FileName.txt");

Response.Charset = "";

Response.Cache.SetCacheability(HttpCacheability.NoCache);

Response.ContentType = "application/vnd.text";

System.IO.StringWriter stringWrite = new System.IO.StringWriter();

System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

Response.Write(str.ToString());

Response.End();

This is it! I hope you like the article, happy coding!