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.
 
Now create the project as:
  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.   
  4.            SaveFileDialog SaveXMLFileDialog = new SaveFileDialog();  
  5.            SaveXMLFileDialog.Filter = "Xml files (*.xml)|*.xml";  
  6.            SaveXMLFileDialog.FilterIndex = 2;  
  7.            SaveXMLFileDialog.RestoreDirectory = true;  
  8.            SaveXMLFileDialog.InitialDirectory = "C:\\";  
  9.            SaveXMLFileDialog.FileName = "Vithal_Wadje";  
  10.            SaveXMLFileDialog.Title = "XML Export";  
  11.            if (SaveXMLFileDialog.ShowDialog() == DialogResult.OK)  
  12.            {  
  13.              
  14.                DataSet ds = new DataSet();  
  15.                DataTable dtxml = (DataTable)ViewState["Data"];  
  16.                ds.Tables.Add(dtxml);  
  17.                ds.WriteXml(File.OpenWrite(SaveXMLFileDialog.FileName));  
  18.                 
  19.            }  
  20.            XMLFileThread.Abort();  
  21.              
  22.        } 
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.           
  7.   
  8.       } 
 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.   
  33.           
  34.         private void Bindgrid()  
  35.         {  
  36.             connection();  
  37.             query = "select *from Employee";//not recommended this i have written just for example,write stored procedure for security  
  38.             com = new SqlCommand(query, con);  
  39.             SqlDataAdapter da = new SqlDataAdapter(query, con);  
  40.             DataSet ds = new DataSet();  
  41.              
  42.             da.Fill(ds);  
  43.             DataTable GridSource = ds.Tables[0];  
  44.             GridView1.DataSource = GridSource;  
  45.             GridView1.DataBind();  
  46.             con.Close();  
  47.             ViewState["Data"] = GridSource;  
  48.         }  
  49.         protected void Button1_Click(object sender, EventArgs e)  
  50.         {  
  51.              XMLFileThread = new Thread(new ThreadStart(ExportGridToXML));  
  52.             XMLFileThread.ApartmentState = ApartmentState.STA;  
  53.             XMLFileThread.Start();  
  54.             
  55.   
  56.         }  
  57.         private void ExportGridToXML()  
  58.         {  
  59.   
  60.             SaveFileDialog SaveXMLFileDialog = new SaveFileDialog();  
  61.             SaveXMLFileDialog.Filter = "Xml files (*.xml)|*.xml";  
  62.             SaveXMLFileDialog.FilterIndex = 2;  
  63.             SaveXMLFileDialog.RestoreDirectory = true;  
  64.             SaveXMLFileDialog.InitialDirectory = "C:\\";  
  65.             SaveXMLFileDialog.FileName = "Vithal_Wadje";  
  66.             SaveXMLFileDialog.Title = "XML Export";  
  67.             if (SaveXMLFileDialog.ShowDialog() == DialogResult.OK)  
  68.             {  
  69.               
  70.                 DataSet ds = new DataSet();  
  71.                 DataTable dtxml = (DataTable)ViewState["Data"];  
  72.                 ds.Tables.Add(dtxml);  
  73.                 ds.WriteXml(File.OpenWrite(SaveXMLFileDialog.FileName));  
  74.                  
  75.             }  
  76.             XMLFileThread.Abort();  
  77.               
  78.         }  
  79.   
  80.          
  81.     }  

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.

Next Recommended Readings