Description:-
In this example we explain that how to bind XML file
data to TreeView in Asp.Net or how to populating the TreeView control with
XMLDataSource in asp.net.or Dynamically bind TreeView from XML file in asp.net.
Here we create a one XML file for country and it's related state and we want to bind this country and it's state to the TreeView Dynamically from the XML file.
So to do this first we have to open the XML file in read/write mode and then we have to fetch it's node one by one and binds it to the TreeView.
Here we create a one XML file for country and it's related state and we want to bind this country and it's state to the TreeView Dynamically from the XML file.
So to do this first we have to open the XML file in read/write mode and then we have to fetch it's node one by one and binds it to the TreeView.
TreeView.aspx:-
<%@
Page Language="C#" AutoEventWireup="true" CodeBehind="TreeView.aspx.cs" Inherits="kiritblog.TreeView"
%>
<!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>Bind or
Populate XML file contents in Treeview in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TreeView ID="TreeView1" runat="server">
</asp:TreeView>
</div>
</form>
</body>
</html>
TreeView.aspx.cs:-
using System;
using
System.Collections.Generic;
using
System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
using
System.Web.UI.WebControls;
namespace kiritblog
{
public partial class TreeView : System.Web.UI.Page
{
protected
void Page_Load(object
sender, EventArgs e)
{
XmlDataDocument
xmldoc = new XmlDataDocument();
XmlNode
xmlnode;
FileStream
fs = new FileStream(@"C:\Users\Kothia\Desktop\kirit\kiritblog\kiritblog\FamilyXML.xml",
FileMode.Open, FileAccess.Read);
xmldoc.Load(fs);
xmlnode = xmldoc.ChildNodes[1];
TreeView1.Nodes.Clear();
TreeView1.Nodes.Add(new TreeNode(xmldoc.DocumentElement.Name));
TreeNode
tNode;
tNode = TreeView1.Nodes[0];
AddNode(xmlnode, tNode);
}
private
void AddNode(XmlNode
inXmlNode, TreeNode inTreeNode)
{
XmlNode
xNode;
TreeNode
tNode;
XmlNodeList
nodeList;
int
i = 0;
if
(inXmlNode.HasChildNodes)
{
nodeList =
inXmlNode.ChildNodes;
for
(i = 0; i <= nodeList.Count - 1; i++)
{
xNode =
inXmlNode.ChildNodes[i];
inTreeNode.ChildNodes.Add(new TreeNode(xNode.Name));
tNode =
inTreeNode.ChildNodes[i];
AddNode(xNode, tNode);
}
}
else
{
inTreeNode.Text =
inXmlNode.InnerText.ToString();
}
}
}
}
0 comments:
Post a Comment