Exporting GridView to Text Files
By AzamSharp
Views: 4213

 

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!

By AzamSharp


Enter Comment/Feedback
  •  
  •  
  •  
  •  
  •  

Comments/Feedbacks
Subject: exporting all pages to text
Name: J
Date: 1/30/2007 4:54:04 AM
Comment:
AzamSharp,

Thanks very much for the code above. Its simple and works great! I used it to add a capability to my web app that allows the user to save a gridview in delimited format. However, I'm not sure as to how I can get all of the pages to save. I tried a couple of different things, but to no avail. Any help is greatly appreciated!



Join WebHost4Life.com






Copyright GridViewGuy 2007-2008