Read XML File & Bind Data to Gridview in Asp.net using C#

Read XML File & Bind Data to Gridview in Asp.net using C#:



Some time we need in asp.net  read data from xml file and display it on webpage. My XML File Name as “Sample.xml” and that would contains data like this


<?xml version="1.0" encoding="utf-8" ?>
<users>
  <user>
    <FirstName>Ram</FirstName>
    <LastName>Kumar</LastName>
    <UserName>RamKumar</UserName>
    <Job>Team Head</Job>
  </user>
  <user>
    <FirstName>Mahesh</FirstName>
    <LastName>Kumar</LastName>
    <UserName>MaheshKumar</UserName>
    <Job>Software Developer</Job>
  </user>
  <user>
    <FirstName>Madhav</FirstName>
    <LastName>Yemineni</LastName>
    <UserName>MadhavYemineni</UserName>
    <Job>Business Analyst</Job>
  </user>

Now I need to get values from this xml file and bind that data to gridview for that write following code in your aspx page like this


<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Read Data from XML and Bind Data to gridview in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="gvDetails" runat="server">
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
</asp:GridView>
</form>
</body>
</html>

Now add following namespaces in codebehind

C# Code


using System;
using System.Data;

Once we add namespaces now add following code in code behind


protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Bind Data to Gridview
GetXMLData();
}
}
// This method is used to get xml node values and bind to gridview
protected void GetXMLData()
{
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("Sample.xml"));
gvDetails.DataSource = ds;
gvDetails.DataBind();

}





Jquery Related Other post:




















Comments