Pages

Monday, August 19, 2013

Display Xml File Data in Gridview in Asp.net.

In previous article we discussed how to read and write xml file data in asp.net. But in this article we are explaining how to display xml file data in gridview. There are many way by which we can display xml file data in gridview. To use xml file data firstly we have use an namespace 'System.Xml'.

Here is xml file data that will be used in project. You can also use xml file from your local drive. In this example we are using xml file in my project.

<?xml version="1.0" encoding="utf-8"?>
<EmployeeData>
  <Details>
    <Name>Jown</Name>
    <Address>Delhi</Address>
    <Mobile>740579959</Mobile>
  </Details>
 
  <Details>
    <Name>Abc</Name>
    <Address>Noida</Address>
    <Mobile>876578667</Mobile>
  </Details>
</EmployeeData>

Method 1
Display xml data using DataTable.              
Add a Gridview control and write following code on page load.

public partial class XmlGridView : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string xmlData = Server.MapPath("EmpData.xml");
        DataTable dataTable = new DataTable("Details");

        dataTable.Columns.Add("Name", typeof(System.String));
        dataTable.Columns.Add("Address", typeof(System.String));
        dataTable.Columns.Add("Mobile", typeof(System.String));

        dataTable.ReadXml(xmlData);
        GridView1.DataSource = dataTable;
        GridView1.DataBind();
    }
}

Method 2
Display xml data using Dataset.
Add a Gridview control and write following code on page load.

public partial class XmlGridView : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        DataSet ds = new DataSet();
        ds.ReadXml(Server.MapPath("EmpData.xml"));
        GridView1.DataSource = ds;
        GridView1.DataBind();

    }

}

No comments:

Post a Comment