public void TreeViewData(DataSet ds,string textColumnName,string parentColumnName,string tagColumnName)
{
myTreeData root = new myTreeData();
myTreeData child = null;
for (i = 0 ; i < ds.Tables[0].Rows.Count; ++i)
{
child = new myTreeData(ds.Tables[0].Rows[i][textColumnName].ToString(),ds.Tables[0].Rows[i][tagColumnName],ds.Tables[0].Rows[i][parentColumnName]);
root.Add(child);
}
root.ShowTree(tv);
}
/// <summary>
/// 树型节点数据类
/// </summary>
public class myTreeData
{
public myTreeData()
{
}
public myTreeData(string name)
{
Name = name;
}
public myTreeData(string name,object tag,object parent)
{
Name = name;
Tag = tag;
Parent = parent;
}
/// <summary>
/// 子数据集合
/// </summary>
private myTreeDataCollection Child = new myTreeDataCollection();
/// <summary>
/// 数据对象
/// </summary>
public object Tag = null;
/// <summary>
/// 名称
/// </summary>
public string Name = "";
/// <summary>
/// 父亲
/// </summary>
public object Parent = null;
/// <summary>
/// 添加子数据
/// </summary>
/// <param name="child">子数据</param>
public void Add(myTreeData child)
{
int i;
for (i = this.Child.Count - 1; i >= 0;--i)
{
if (Convert.ToInt32(this.Child[i].Parent) == Convert.ToInt32(child.Tag) )
{
child.Child.Add(this.Child[i]);
this.Child.RemoveAt(i);
}
}
myTreeData parent = FindParent(this,child);
if (parent == null)
{
this.Child.Add(child);
}
else
{
parent.Child.Add(child);
}
}
/// <summary>
/// 查找父亲数据
/// </summary>
/// <param name="child">子数据</param>
/// <returns>父亲数据或者null</returns>
public myTreeData FindParent(myTreeData parent,myTreeData child)
{
int i;
for (i = 0; i < parent.Child.Count; ++i)
{
if (Convert.ToInt32(parent.Child[i].Tag) == Convert.ToInt32(child.Parent))
{
return parent.Child[i];
}
myTreeData temp = FindParent(parent.Child[i],child);
if (temp != null)
{
return temp;
}
}
return null;
}
/// <summary>
/// 将子数据显示到TreeView
/// </summary>
/// <param name="tv">TreeView</param>
public void ShowTree(TreeView tv)
{
int i;
TreeNode tn = null;
for (i = 0 ; i < this.Child.Count; ++i)
{
tn = tv.Nodes.Add(this.Child[i].Name);
tn.Tag = this.Child[i].Tag;
ShowTree(tn,this.Child[i]);
}
}
/// <summary>
/// 递归显示数据
/// </summary>
/// <param name="tn">节点</param>
/// <param name="child">数据</param>
private void ShowTree(TreeNode tnParent,myTreeData child)
{
int i;
TreeNode tn = null;
for (i = 0 ; i < child.Child.Count; ++i)
{
tn = tnParent.Nodes.Add(child.Child[i].Name);
tn.Tag = child.Child[i].Tag;
ShowTree(tn,child.Child[i]);
}
}
/// <summary>
/// 树型节点集合类
/// </summary>
internal class myTreeDataCollection : AddCollectionBase
{
public myTreeDataCollection()
{
}
public myTreeData this[int index]
{
get
{
return (myTreeData)List[index];
}
}
}
}
本文地址:http://com.8s8s.com/it/it41222.htm