要获得树的整个展开的状态比较困难,但是我们可以只刷新树中节点(node)的内容来实现这种功能。如果需要保存一些数据的关联信息,可以存储在TreeNode.Tag属性中。
代码:
private Hashtable _nodesByValueMember = new Hashtable();// 存储所有的树节点
private void Form4_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);
this.dataGridView1.DataSource = dt;// DataGridView用来修改树节点的内容
this.dataGridView1.Columns[0].Visible = false;
this.dataGridView1.Columns[1].Visible = false;
this.dataGridView1.AllowUserToAddRows = false;
}
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.");
}
}
}
}
private void btnrefresh_Click(object sender, EventArgs e)
{
//刷新节点的文本
DataTable dt = (DataTable)this.dataGridView1.DataSource;
foreach (DataRow dr in dt.Rows)
{
TreeNode node = (TreeNode)_nodesByValueMember[dr["ID"].ToString()];
node.Text = dr["Name"].ToString();
}
}