Export GridView Records to XML Using ASP.Net C#

Background


There is often a need in a project's reporting module to export GridView Records to XML. So by considering that requirement I decided to write this article especially focusing on beginners and those who want to learn how to export a GridView to XML using ASP.NET C#.
 
Now before creating the application, let us create a table named employee in a database from where we show the records in a Grid view, the table has the following fields (shown in the following image):
 
 
I hope you have created the same type of table.
  1. "Start" - "All Programs" - "Microsoft Visual Studio 2010".
  2. "File" - "New Project" - "C#" - "Empty Project" (to avoid adding a master page).
  3. Provide the Project name such as ExportGridRecordsToXML or another as you wish and specify the location.
  4. Then right-click on Solution Explorer - "Add New Item" - Default.aspx page.
  5. One Button and a grid view.

Now the default.aspx source code will be such as follows:

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ExPortGridviewToXML.Default" %>  
  2.   
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  4. <html>  
  5. <head id="Head1" runat="server">  
  6.     <title></title>  
  7. </head>  
  8. <body bgcolor="Silver">  
  9.     <form id="form1" runat="server">  
  10.     <br />  
  11.     <h2 style="color: #808000; font-size: x-large; font-weight: bolder;">  
  12.         Article by Vithal Wadje</h2>  
  13.     <br />  
  14.     <div>  
  15.         <asp:GridView ID="GridView1" runat="server" CellPadding="6" ForeColor="#333333" GridLines="None">  
  16.             <AlternatingRowStyle BackColor="White" />  
  17.             <EditRowStyle BackColor="#7C6F57" />  
  18.             <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />  
  19.             <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />  
  20.             <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />  
  21.             <RowStyle BackColor="#E3EAEB" />  
  22.             <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />  
  23.             <SortedAscendingCellStyle BackColor="#F8FAFA" />  
  24.             <SortedAscendingHeaderStyle BackColor="#246B61" />  
  25.             <SortedDescendingCellStyle BackColor="#D4DFE1" />  
  26.             <SortedDescendingHeaderStyle BackColor="#15524A" />  
  27.         </asp:GridView>  
  28.         <br />  
  29.                    <asp:Button ID="Button1" runat="server"  
  30.             Text="Export" OnClick="Button1_Click" />  
  31.     </div>  
  32.     </form>  
  33. </body>  
  34. </html> 

Now let us create a function to bind the records to the Grid view from the database. If you are a beginner and don't understand in detail how to bind a Grid view from a database then refer to my following article.

Now, for this article create the following function in the default.aspx.cs page to bind the Grid view:

  1. private void Bindgrid()    
  2. {    
  3.     connection();    
  4.     query = "select *from Employee";//not recommended this i have written just for example,write stored procedure for security    
  5.     com = new SqlCommand(query, con);    
  6.     SqlDataAdapter da = new SqlDataAdapter(query, con);    
  7.     DataSet ds = new DataSet();    
  8.        
  9.     da.Fill(ds);    
  10.     DataTable GridSource = ds.Tables[0];    
  11.     GridView1.DataSource = GridSource;    
  12.     GridView1.DataBind();    
  13.     con.Close();    
  14.     ViewState["Data"] = GridSource;    
  15. } 
Now, call the preceding function on page load as:
  1. protected void Page_Load(object sender, EventArgs e)    
  2. {    
  3.     if (!IsPostBack)    
  4.     {    
  5.         Bindgrid();    
  6.   
  7.     }    
  8. } 
Now create the following function to export the Grid view records to XML:
  1. private void ExportGridToXML()    
  2. {  
  3.     SaveFileDialog SaveXMLFileDialog = new SaveFileDialog();    
  4.     SaveXMLFileDialog.Filter = "Xml files (*.xml)|*.xml";    
  5.     SaveXMLFileDialog.FilterIndex = 2;    
  6.     SaveXMLFileDialog.RestoreDirectory = true;    
  7.     SaveXMLFileDialog.InitialDirectory = "C:\\";    
  8.     SaveXMLFileDialog.FileName = "Vithal_Wadje";    
  9.     SaveXMLFileDialog.Title = "XML Export";    
  10.     if (SaveXMLFileDialog.ShowDialog() == DialogResult.OK)    
  11.     {        
  12.         DataSet ds = new DataSet();    
  13.         DataTable dtxml = (DataTable)ViewState["Data"];    
  14.         ds.Tables.Add(dtxml);    
  15.         ds.WriteXml(File.OpenWrite(SaveXMLFileDialog.FileName));           
  16.     }    
  17.     XMLFileThread.Abort();        
  18. } 
We have created the preceding function that is used to export the dataTable to XML that is used for a GridView as a DataSource.
 
Now call the preceding function on the Export button click as: 
  1. protected void Button1_Click(object sender, EventArgs e)    
  2. {    
  3.      XMLFileThread = new Thread(new ThreadStart(ExportGridToXML));    
  4.     XMLFileThread.ApartmentState = ApartmentState.STA;    
  5.     XMLFileThread.Start();  
  6. } 
The entire code of the default.aspx page will look such as follows:
  1. using System;  
  2. using System.IO;  
  3. using System.Windows.Forms;  
  4. using System.Data;  
  5. using System.Threading;  
  6. using System.Data.SqlClient;  
  7. using System.Configuration;  
  8.   
  9. namespace ExPortGridviewToXML  
  10. {  
  11.     public partial class Default : System.Web.UI.Page  
  12.     {  
  13.         private SqlConnection con;  
  14.         private SqlCommand com;  
  15.         private string constr, query;  
  16.         Thread XMLFileThread;  
  17.         private void connection()  
  18.         {  
  19.             constr = ConfigurationManager.ConnectionStrings["getconn"].ToString();  
  20.             con = new SqlConnection(constr);  
  21.             con.Open();  
  22.   
  23.         }  
  24.         protected void Page_Load(object sender, EventArgs e)  
  25.         {  
  26.             if (!IsPostBack)  
  27.             {  
  28.                 Bindgrid();  
  29.   
  30.             }  
  31.         }
  32.         private void Bindgrid()  
  33.         {  
  34.             connection();  
  35.             query = "select *from Employee";//not recommended this i have written just for example,write stored procedure for security  
  36.             com = new SqlCommand(query, con);  
  37.             SqlDataAdapter da = new SqlDataAdapter(query, con);  
  38.             DataSet ds = new DataSet();  
  39.              
  40.             da.Fill(ds);  
  41.             DataTable GridSource = ds.Tables[0];  
  42.             GridView1.DataSource = GridSource;  
  43.             GridView1.DataBind();  
  44.             con.Close();  
  45.             ViewState["Data"] = GridSource;  
  46.         }  
  47.         protected void Button1_Click(object sender, EventArgs e)  
  48.         {  
  49.              XMLFileThread = new Thread(new ThreadStart(ExportGridToXML));  
  50.             XMLFileThread.ApartmentState = ApartmentState.STA;  
  51.             XMLFileThread.Start();
  52.         }  
  53.         private void ExportGridToXML()  
  54.         {  
  55.   
  56.             SaveFileDialog SaveXMLFileDialog = new SaveFileDialog();  
  57.             SaveXMLFileDialog.Filter = "Xml files (*.xml)|*.xml";  
  58.             SaveXMLFileDialog.FilterIndex = 2;  
  59.             SaveXMLFileDialog.RestoreDirectory = true;  
  60.             SaveXMLFileDialog.InitialDirectory = "C:\\";  
  61.             SaveXMLFileDialog.FileName = "Vithal_Wadje";  
  62.             SaveXMLFileDialog.Title = "XML Export";  
  63.             if (SaveXMLFileDialog.ShowDialog() == DialogResult.OK)  
  64.             {  
  65.               
  66.                 DataSet ds = new DataSet();  
  67.                 DataTable dtxml = (DataTable)ViewState["Data"];  
  68.                 ds.Tables.Add(dtxml);  
  69.                 ds.WriteXml(File.OpenWrite(SaveXMLFileDialog.FileName));  
  70.                  
  71.             }  
  72.             XMLFileThread.Abort();  
  73.               
  74.         }
  75.     }  

Now run the application and then we can see the following records in the Grid view:
 
 
Now click on the export button. The XML file that is created will be saved on my Desktop because I have given the C drive path in the code, however you can specify any path as you wish, the file will look such as follows:
 
 
 
Now open the file using Visual Studio or any browser. I will open it with the IE browser then the records will look such as follows:
 
 
Now you see that all the records of the Grid view are exported to an XML file.

Notes
  • Download the Zip file from the attachment for the full source code of the application.
  • Change the connection string in the web.config file to specify your server location.
  • You can save the XML file that is created to any location.
  • We are actually exporting the Data Table to XML that is used for a Grid view as a Data Source.
Summary

I hope this article is useful for all readers, if you have any suggestion then please contact me including beginners also.


Similar Articles