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. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. <html>
  4. <head id="Head1" runat="server">
  5. <title></title>
  6. </head>
  7. <body bgcolor="Silver">
  8. <form id="form1" runat="server">
  9. <br />
  10. <h2 style="color: #808000; font-size: x-large; font-weight: bolder;">
  11. Article by Vithal Wadje</h2>
  12. <br />
  13. <div>
  14. <asp:GridView ID="GridView1" runat="server" CellPadding="6" ForeColor="#333333" GridLines="None">
  15. <AlternatingRowStyle BackColor="White" />
  16. <EditRowStyle BackColor="#7C6F57" />
  17. <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
  18. <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
  19. <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
  20. <RowStyle BackColor="#E3EAEB" />
  21. <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
  22. <SortedAscendingCellStyle BackColor="#F8FAFA" />
  23. <SortedAscendingHeaderStyle BackColor="#246B61" />
  24. <SortedDescendingCellStyle BackColor="#D4DFE1" />
  25. <SortedDescendingHeaderStyle BackColor="#15524A" />
  26. </asp:GridView>
  27. <br />
  28. <asp:Button ID="Button1" runat="server"
  29. Text="Export" OnClick="Button1_Click" />
  30. </div>
  31. </form>
  32. </body>
  33. </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. da.Fill(ds);
  9. DataTable GridSource = ds.Tables[0];
  10. GridView1.DataSource = GridSource;
  11. GridView1.DataBind();
  12. con.Close();
  13. ViewState["Data"] = GridSource;
  14. }
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. }
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. namespace ExPortGridviewToXML
  9. {
  10. public partial class Default : System.Web.UI.Page
  11. {
  12. private SqlConnection con;
  13. private SqlCommand com;
  14. private string constr, query;
  15. Thread XMLFileThread;
  16. private void connection()
  17. {
  18. constr = ConfigurationManager.ConnectionStrings["getconn"].ToString();
  19. con = new SqlConnection(constr);
  20. con.Open();
  21. }
  22. protected void Page_Load(object sender, EventArgs e)
  23. {
  24. if (!IsPostBack)
  25. {
  26. Bindgrid();
  27. }
  28. }
  29. private void Bindgrid()
  30. {
  31. connection();
  32. query = "select *from Employee";//not recommended this i have written just for example,write stored procedure for security
  33. com = new SqlCommand(query, con);
  34. SqlDataAdapter da = new SqlDataAdapter(query, con);
  35. DataSet ds = new DataSet();
  36. da.Fill(ds);
  37. DataTable GridSource = ds.Tables[0];
  38. GridView1.DataSource = GridSource;
  39. GridView1.DataBind();
  40. con.Close();
  41. ViewState["Data"] = GridSource;
  42. }
  43. protected void Button1_Click(object sender, EventArgs e)
  44. {
  45. XMLFileThread = new Thread(new ThreadStart(ExportGridToXML));
  46. XMLFileThread.ApartmentState = ApartmentState.STA;
  47. XMLFileThread.Start();
  48. }
  49. private void ExportGridToXML()
  50. {
  51. SaveFileDialog SaveXMLFileDialog = new SaveFileDialog();
  52. SaveXMLFileDialog.Filter = "Xml files (*.xml)|*.xml";
  53. SaveXMLFileDialog.FilterIndex = 2;
  54. SaveXMLFileDialog.RestoreDirectory = true;
  55. SaveXMLFileDialog.InitialDirectory = "C:\\";
  56. SaveXMLFileDialog.FileName = "Vithal_Wadje";
  57. SaveXMLFileDialog.Title = "XML Export";
  58. if (SaveXMLFileDialog.ShowDialog() == DialogResult.OK)
  59. {
  60. DataSet ds = new DataSet();
  61. DataTable dtxml = (DataTable)ViewState["Data"];
  62. ds.Tables.Add(dtxml);
  63. ds.WriteXml(File.OpenWrite(SaveXMLFileDialog.FileName));
  64. }
  65. XMLFileThread.Abort();
  66. }
  67. }
  68. }
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.