serge calderara wrote:
dear all,
Is there an easy way to bind a treeview control with an XML object as
datasource?
In a similar way as the dataset is doing, and build columns accroding to
XML node, I could imagine a treeview which build its notes accordind to XML
object too
how can I do that?
thanks for wour help
serge
Funny you should ask, becase I am working on a project where i do just
that. I am retrieving XML data from a web service and I use that to
populate a tree control. My XML data is highly tailored to the
application, which is why you see special parsing in the AddNode method.
private void populateBox()
{
//Object[] objarray = lc.AllLocations ();
lcx = lc.LocationsTop Level();
try
{
// SECTION 1. Create a DOM Document and load the XML data into it.
XmlDocument dom = new XmlDocument();
//dom.AppendChild (lcx);
//dom.Load(textBo x1.Text);
dom.AppendChild (dom.ImportNode (
lcx
,true));
//inXmlNode=inXml Node.SelectSing leNode("//position[@row='1']");
// SECTION 2. Initialize the TreeView control.
treeView1.Nodes .Clear();
treeView1.Nodes .Add(new TreeNode(dom.Do cumentElement.N ame));
TreeNode tNode = new TreeNode();
tNode = treeView1.Nodes[0];
// SECTION 3. Populate the TreeView with the DOM nodes.
AddNode(dom.Doc umentElement, tNode);
treeView1.Expan dAll();
}
catch(XmlExcept ion xmlEx)
{
MessageBox.Show (xmlEx.Message) ;
}
catch(Exception ex)
{
MessageBox.Show (ex.Message);
}
}
private void AddNode(XmlNode inXmlNode, TreeNode inTreeNode)
{
XmlNode xNode;
TreeNode tNode;
XmlNodeList nodeList;
int i;
// Loop through the XML nodes until the leaf is reached.
// Add the nodes to the TreeView during the looping process.
try
{
if (inXmlNode.HasC hildNodes)
{
nodeList = inXmlNode.Child Nodes;
for(i = 0; i<=nodeList.Cou nt - 1; i++)
{
xNode = inXmlNode.Child Nodes[i];
if(xNode.Name== "position")
inTreeNode.Node s.Add(new TreeNode(
xNode.Attribute s.GetNamedItem( "row").InnerTex t.ToString() + " " +
xNode.Attribute s.GetNamedItem( "bay").InnerTex t.ToString() + " " +
xNode.Attribute s.GetNamedItem( "level").InnerT ext.ToString()
));
if(xNode.Name== "client")
inTreeNode.Node s.Add(new TreeNode(
xNode.Attribute s.GetNamedItem( "id").InnerText .ToString()));
if(xNode.Name== "partnum")
inTreeNode.Node s.Add(new TreeNode(
xNode.InnerText ));
tNode = inTreeNode.Node s[i];
AddNode(xNode, tNode);
}
}
else
{
// Here you need to pull the data from the XmlNode based on the
// type of node, whether attribute values are required, and so forth.
//inTreeNode.Text = (inXmlNode.Oute rXml).Trim();
//inTreeNode.Text = (inXmlNode.Inne rText).Trim();
if(inXmlNode.Na me=="position")
inTreeNode.Node s.Add(new TreeNode(
inXmlNode.Attri butes.GetNamedI tem("row").Inne rText.ToString( ) + " " +
inXmlNode.Attri butes.GetNamedI tem("bay").Inne rText.ToString( ) + " " +
inXmlNode.Attri butes.GetNamedI tem("level").In nerText.ToStrin g()
));
}
}
catch (Exception e)
{
Debug.WriteLine (e.ToString());
}
}