Friday, November 25, 2011

XML data into Gridview in asp.net

Title:how to bind XML data in grid view in asp.net using C#.net

Description:
We have seen different examples on  how to bind data to Grid view in asp.net ,Import XML data to Grid View,bind data table to Grid view.Now i would like show how to bind the XML data to grid view.Before going to start  you may think we have to use XML classes to read the data,But we will not use any XML classes .In asp.net Data set has property to read the XML data which is Readxml().
XML Data:
<?xml version="1.0" encoding="utf-8" ?>
<Orders>
<Order>
<OrderId>1</OrderId>
<OrderName>Asp.net</OrderName>
<Phone>0000000000</Phone>
<Address>Hyd</Address>
<Amount>100</Amount>
</Order>
<Order>
<OrderId>2</OrderId>
<OrderName>Sharepoint</OrderName>
<Phone>1111111111</Phone>
<Address>USA</Address>
<Amount>200</Amount>
</Order>
<Order>
<OrderId>3</OrderId>
<OrderName>Jquery</OrderName>
<Phone>2222222222</Phone>
<Address>UK</Address>
<Amount>200</Amount>
</Order>
<Order>
<OrderId>4</OrderId>
<OrderName>Mvc</OrderName>
<Phone>4444444444</Phone>
<Address>AUS</Address>
<Amount>300</Amount>
</Order>
</Orders>

Aspx Page:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Bind XML data to Gridview in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GVdynamicXML" runat="server" AutoGenerateColumns="False"
>
<Columns>
<asp:BoundField DataField="OrderID" HeaderText="OrderID"
 SortExpression="OrderID" />
<asp:BoundField DataField="OrderName" HeaderText="OrderName"
 SortExpression="OrderName" />
<asp:BoundField DataField="Phone" HeaderText="Phone" SortExpression="Phone" />
<asp:BoundField DataField="Address" HeaderText="Address"
SortExpression="Address" />
<asp:BoundField DataField="Amount" HeaderText="Amount"
SortExpression="Amount" />
</Columns>
</asp:GridView>
</form>
</body>
</html>

Code behind:
using System;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

public partial class _XMLbindGridviewDefault3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet myDataSet = new DataSet();
myDataSet.ReadXml(Server.MapPath("~/XMLFile.xml"));
GVdynamicXML.DataSource = myDataSet;
GVdynamicXML.DataBind();
}
}
}
We should give a specific path of XML file to read the data using Readxml().Then bind the data  to grid view "gd_view"
Post a Comment

Bel