Thursday, 18 October 2012

C#.net How to: Load and display XML data in ASP.net

This C# Tutorial will give you a step by step procedure to load xml into DataSet and then bind that data to Gridview in ASP.net. So at the end of this tutorial you will have a clear understanding on how to load xml data in DataSet and then bind & display the xml in GridView.

What i observed is very less information available in internet on how to load xml file in asp.net. Hence i thought to write up an article that explains step by step procedure with screenshot so that it would be helpful for beginners.
Display XML in Asp.net
Display XML in Asp.net
To start with this tutorial, first you will need xml file. So in this article we are taking an example of xml file that contains various Camera Details such as Camera make model name and prices. Take a look at below contents of the xml file that we are going to use for this tutorial. You can create an xml file in Visual studio by clicking File -> New -> File or by simply clicking Ctrl+N and then double click on XML File option. Delete all automated contents and then copy paste below contents and save the file with name "CameraDetails.xml". Save this file anywhere on your local disk, however in next few steps we are going to copy this file in project location so just take a note of file location.

XML File.

<?xml version="1.0" encoding="utf-8"?>
<Cameras>
  <Camera>
    <Model>Canon EOS-1D</Model>
    <Price>$5219</Price>
  </Camera>
  <Camera>
    <Model>Canon EOS-1D Mark IV</Model>
    <Price>$5000</Price>
  </Camera>
  <Camera>
    <Model>Canon EOS 5D Mark III</Model>
    <Price>$2949</Price>
  </Camera>
  <Camera>
    <Model>Nikon DSLR D3100 Black</Model>
    <Price>$1222</Price>
  </Camera>
  <Camera>
    <Model>Sony CyberShot DSC T99</Model>
    <Price>$178</Price>
  </Camera>
  <Camera>
    <Model>Samsung PL20 Silver</Model>
    <Price>$101</Price>
  </Camera
</Cameras>
So the basic idea here is that we would be having a xml file, we would load xml file to DataSet and would bind that DataSet to GridView. The final output at the end of this tutorial will be like –
Camera Make Model
Price
Canon EOS-1D
$5219
Canon EOS-1D Mark IV
$5000
Canon EOS 5D Mark III
$2949
Nikon DSLR D3100 Black
$1222
Sony CyberShot DSC T99
$178
Samsung PL20 Silver
$101

Steps to load and display xml in Asp.net GridView

  1. Open Visual Studio 2010 .net IDE to create a new asp.net project.
  2. Select File -> New -> Project or simply click Ctrl+Shift+N to create a new ASP.net project.
  3. Select Web from left pane and then select ASP.NET Web Application from right pane, enter your desired project name, location of the project and click on OK button.
    Create New Web Application
    Create New Web Application
  4. Now copy the xml "CameraDetails.xml" that we have created in initial steps to your project folder.
  5. In this article we are going to display xml in aspx page hence in this step we would create a new web page that would display output i.e. xml data.

    To create a new page go to solution explorer, right click on project name, select Add from the context menu and then select New Item from submenu. Or simply press Ctrl+Shift+A to add a new item. And then Select Web Form, enter name for the web page, here i have named it as "CameraDetails.aspx". Once done click on Add button.
    Add new ASPX page
    Add new ASPX page
    You can see this newly added web page in Solution Explorer.
  6. Now right click on the "CameraDetails.aspx" aspx page in solution explorer and select View Designer to open the page in design mode.
  7. To display xml in GridView we need to place GridView control on this aspx page.

    To add GridView this page, go to Toolbar and select GridView and drag & drop in page. So the design page would be like below screenshot –
    GridView in asp.net
    GridView in asp.net
  8. You can view the source code of this design by clicking source on bottom of the window. Click on Source and it would open a source of the page that would be essentially a HTML look.
    Source View
    Souce view
  9. You may see following lines in opened source page.
           <asp:GridView ID="GridView1" runat="server">
            </asp:GridView>
     
  10. Now replace above lines with following contents –
            <asp:GridView ID="gridCameraDetails" runat="server" AutoGenerateColumns="False" CellPadding="8"
                HeaderStyle-BackColor="Menu" HeaderStyle-ForeColor="blue" HeaderStyle-HorizontalAlign="Center"
                HeaderStyle-Font-Bold="True" RowStyle-BackColor="AliceBlue">
                <Columns>
                    <asp:BoundField HeaderText="Camera Make Model" DataField="Model" ItemStyle-HorizontalAlign="Right" />
                    <asp:BoundField HeaderText="Price" DataField="Price" ItemStyle-HorizontalAlign="Left" />
                </Columns>
            </asp:GridView>
  11. Find <title> and enter the title "Camera Details". Save the changes.
  12. Again go to Solution explorer, right click on this page, select View Code from context menu. It will open a CameraDetails.aspx.cs file where you can write your actual C#.net code.
  13. Add below lines in your code. This is a namespace that imports DataSet in your code.
            using System.Data;
  14. The idea here is to load xml in Page_Load event. Hence we need to find and replace auto generated Page_Load event. locate following lines -
            protected void Page_Load(object sender, EventArgs e)
            {

            }
  15. Now replace above mentioned complete Page_Load event with below C# code –
            protected void Page_Load(object sender, EventArgs e)
            {
                try
                {
                    var xmlFilePath = Server.MapPath("CameraDetails.xml");//Location of the XML file.
                    DataSet dsCameraDetails = new DataSet();
                    dsCameraDetails.ReadXml(xmlFilePath);// Load XML in dataset
                    gridCameraDetails.DataSource = dsCameraDetails.Tables[0].DefaultView;
                    gridCameraDetails.DataBind();// Bind the DataSet to Grid that will display all xml data.
                }
                catch (Exception ex)
                {
                    //handle exception here...
                }
            }
  16. Save all files and we are done with coding and designing part to display xml in Gridview.
  17. Go to solution explorer, right click on "CameraDetails" and select Set As Startup Page.
  18. Now execute the ASP.net project and see the output. To execute the web application press F5 button. You will notice gridview display xml data in asp.net page.
I hope this article helped you to understand how to display xml in asp.net page. Could you please share the article on your favorite social media using below widget?

More articles on Asp.net...

Protected by Copyscape Plagiarism Check

Sharing is Caring...





10 comments:

  1. Thanks a lot
    your explanation was very clear ,,
    Would you mind explaining to us the reverse (how to Build a form to upload xml file)

    regards
    asma

    ReplyDelete
    Replies
    1. Thanks for the comments. Your question is not clear to me. Could you please explain what is needed?

      Delete
    2. useing a XML file so that the data is stored and retrieved in XML using the gridview in ASP.NET.

      Delete
  2. i searched in the internet for an explanation and you were the best in writing comments it was very clear..
    Thank you ..

    ReplyDelete
  3. Nice post. Got a lot of important stuff from this blog.
    dba kings

    ReplyDelete
  4. good Post....Thanx.....

    ReplyDelete
  5. Well its nice working dude...

    ReplyDelete