Bind xml data to dropdownlist or gridview in asp.net

 In asp.net how to bind xml data to drop down list or gridview in asp.net:


In previous post I explained post relating to XML some of those are read xml file and bind data to Asp.net grid view and how to insert and read data from xml in asp.net. In situation I got requirement like read data from xml file and display it on webpage. My XML File Name as “SampleDemofor.xml” and that would contains data like this

<?xml version="1.0" encoding="utf-8" ?>
<users>
          <user>
                   <FirstName>Parijat</FirstName>
                   <LastName>Mishra</LastName>
                   <UserName>ParijatMishra</UserName>
                   <Job>Software Team Leader </Job>
          </user>
          <user>
                   <FirstName>Parijat1</FirstName>
                   <LastName>Mishra</LastName>
                   <UserName>ParijatMishra1</UserName>
                   <Job>Software Developer in asp.net</Job>
          </user>
          
</users>

Now We need to get values from this xml file and bind that data to gridview and dropdownlist for that first create xml file in your application and give name as “SampleDemoforXML.xml” and write following code in your aspx page like this

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Read Data from XML and Bind Data to gridview/dropdownlist in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<table>
<tr>
<td><b>Dropdown List</b></td>
<td><asp:DropDownList ID="ddlDetails" runat="server"/></td>
</tr>
<tr>
<td><b>Gridview Details</b></td>
<td>
<asp:GridView ID="gvDetails" runat="server">
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
</asp:GridView>
</td>
</tr>
</table>
</form>
</body>
</html>

C# Code bind from XML Data:



using System;
using System.Data;
using System.Xml;



protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindDataToGridviewDropdownlist();
}
}


protected void BindDataToGridviewDropdownlist()
{
XmlTextReader xmlreader = new XmlTextReader(Server.MapPath("SampleDemofor.xml"));
DataSet ds = new DataSet();
ds.ReadXml(xmlreader);
xmlreader.Close();
if (ds.Tables.Count != 0)
{
//Bind Data to gridview
gvDetails.DataSource = ds;
gvDetails.DataBind();
//Bind Data to dropdownlist
ddlDetails.DataSource = ds;
ddlDetails.DataTextField = "UserName";
ddlDetails.DataValueField = "UserName";
ddlDetails.DataBind();
}

}

Other Related Post :








Comments