首先,需要为所有的数据创建树节点(tree node),然后用哈希表(hash table)存储这些树节点(tree node),最后遍历整张哈希表(hash table)根据存储的信息分层次地给TreeView添加树节点。请参考以下代码:
代码:
namespace TreeView
{
public partial class BindingTreeView : Form
{
public BindingTreeView()
{
InitializeComponent();
}
private Hashtable _nodesByValueMember = new Hashtable();// 存储所有的树节点
private void BindingTreeView_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("IDParent", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Rows.Add(new object[] { 1, 2, null });
dt.Rows.Add(new object[] { 2, 0, "Sports News" });
dt.Rows.Add(new object[] { 3, 2, "Rugby" });
dt.Rows.Add(new object[] { 4, 1, "Amateur Soccer" });
dt.Rows.Add(new object[] { 5, 1, "Proffesional Soccer" });
dt.Rows.Add(new object[] { 6, 0, "International News" });
dt.AcceptChanges();
this.treeView1.Nodes.Clear();
binding(dt);
}
private void binding(DataTable dt)
{
foreach (DataRow dr in dt.Rows)
{
TreeNode node = new TreeNode(dr["name"].ToString());
node.Name = dr["ID"].ToString();
node.Tag = dr["IDParent"];
_nodesByValueMember.Add(node.Name, node);
}
foreach (TreeNode node in _nodesByValueMember.Values)
{
if (node.Tag.ToString() == "0")
{
//如果节点是根节点,添加到根集合中
this.treeView1.Nodes.Add(node);
}
else
{
//寻找父节点
TreeNode parent = (TreeNode)_nodesByValueMember[node.Tag.ToString()];
if (parent != null)
{
//添加到父节点的节点集合中
parent.Nodes.Add(node);
}
else
{
throw new ArgumentException("Node with Value = " + Convert.ToString(node.Tag) + " does not exist. The referencing node has a value = " + Convert.ToString(node.Tag) + ". Check your datasource integrity.");
}
}
}
}
}
}