In this article I’m going to explain how to bind GridView from XML file in ASP.NET using C#.
I’ve already written few articles about XML. In this article I’ll show you how to bind GridView from XML.
First we have to create XML file and write some sample data about employee details. Then we’ve to read that data from XML file and we can display the data to GridView.
So first we should create XML file

Here we've to write some sample data
<?xml version="1.0" encoding="utf-8" ?>
<EmployeeDetails>
<Employee>
<empid>1001</empid>
<name>Sachin</name>
<designation>Software Engineer</designation>
<city>Chennai</city>
<country>India</country>
</Employee>
<Employee>
<empid>1002</empid>
<name>Suresh</name>
<designation>Web Developer</designation>
<city>New Delhi</city>
<country>India</country>
</Employee>
<Employee>
<empid>1003</empid>
<name>Steve</name>
<designation>Web Developer</designation>
<city>Bangalore</city>
<country>India</country>
</Employee>
<Employee>
<empid>1004</empid>
<name>Karthik</name>
<designation>Business Analyst</designation>
<city>New Delhi</city>
<country>India</country>
</Employee>
</EmployeeDetails>
Designer source code:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvEmployee" runat="server" AutoGenerateColumns="false" Width="600px">
<HeaderStyle BackColor="#3E3E3E" Font-Bold="True" Font-Names="cambria" ForeColor="White" />
<RowStyle Font-Names="Calibri" />
<Columns>
<asp:BoundField DataField="empid" HeaderText="Employee ID" />
<asp:BoundField DataField="name" HeaderText="Name" />
<asp:BoundField DataField="designation" HeaderText="Designation" />
<asp:BoundField DataField="city" HeaderText="City" />
<asp:BoundField DataField="country" HeaderText="Country" />
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
Code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class _Default :
System.Web.UI.Page
{
protected void Page_Load(object
sender, EventArgs e)
{
if
(!IsPostBack)
{
BindData();
}
}
protected void BindData()
{
DataSet ds = new
DataSet();
try
{
ds.ReadXml(Server.MapPath("EmployeeDetails.xml"));
if
(ds != null && ds.HasChanges())
{
gvEmployee.DataSource = ds;
gvEmployee.DataBind();
}
else
{
gvEmployee.DataBind();
}
}
catch (Exception ex)
{
}
}
}