在BugTiger中用到了TreeView,数据更新时需要对TreeView的Nodes进行相应的更新(增删改).如果直接对TreeView进行操作,非常的麻烦,因为数据是以DataSet的形式从服务器上取得的,直接操作就要先遍历TreeView,处理删除和修改过的节点,然后遍历DataSet,处理新增加的节点.这里最大难点是TreeNode和DataSet中数据的对应关系.最后还是放弃了这个方法,我选择了先把所有Nodes清空掉,然后重新添加Nodes.这样的又带来一个问题,如何保持原TreeView的状态.这里的状态指节点的展开和折叠以及选中的节点.
<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
解决:
我使用Hashtable来保存每个节点的状态.在把所有Nodes清空掉之前遍历TreeView,取得每个节点的状态,然后根据DataSet重新添加Nodes,添加完成后得根据刚才建立的Hashtable信息来设置每个节点的状态.
代码 :
重新添加节点
private
void
Rebuild()
{
GetTreeNodesStatus(treeView1.Nodes);
treeView1.Nodes.Clear();
TreeNode node1 = new TreeNode( " Node1 " );
node1.Nodes.Add( new TreeNode( " Node1 1 " ));
node1.Nodes.Add( new TreeNode( " Node1 2 " ));
node1.Nodes.Add( new TreeNode( " Node1 3 " ));
TreeNode node2 = new TreeNode( " Node2 " );
node2.Nodes.Add( new TreeNode( " Node2 1 " ));
node2.Nodes.Add( new TreeNode( " Node1 2 " ));
TreeNode node3 = new TreeNode( " Node3 " );
treeView1.Nodes.Add(node1);
treeView1.Nodes.Add(node2);
treeView1.Nodes.Add(node3);
SetTreeNodesStatus(treeView1.Nodes);
}
{
GetTreeNodesStatus(treeView1.Nodes);
treeView1.Nodes.Clear();
TreeNode node1 = new TreeNode( " Node1 " );
node1.Nodes.Add( new TreeNode( " Node1 1 " ));
node1.Nodes.Add( new TreeNode( " Node1 2 " ));
node1.Nodes.Add( new TreeNode( " Node1 3 " ));
TreeNode node2 = new TreeNode( " Node2 " );
node2.Nodes.Add( new TreeNode( " Node2 1 " ));
node2.Nodes.Add( new TreeNode( " Node1 2 " ));
TreeNode node3 = new TreeNode( " Node3 " );
treeView1.Nodes.Add(node1);
treeView1.Nodes.Add(node2);
treeView1.Nodes.Add(node3);
SetTreeNodesStatus(treeView1.Nodes);
}
保存TreeNode状态
private
void
GetTreeNodesStatus(TreeNodeCollection nodes)
{
foreach (TreeNode node in nodes)
{
if (node.IsExpanded)
{
NodesStatus[node.FullPath] = true ;
}
else
{
NodesStatus.Remove(node.FullPath);
}
if (node.IsSelected)
{
SelectNodeFullPath = node.FullPath;
}
GetTreeNodesStatus(node.Nodes);
}
}
{
foreach (TreeNode node in nodes)
{
if (node.IsExpanded)
{
NodesStatus[node.FullPath] = true ;
}
else
{
NodesStatus.Remove(node.FullPath);
}
if (node.IsSelected)
{
SelectNodeFullPath = node.FullPath;
}
GetTreeNodesStatus(node.Nodes);
}
}
设置TreeNode状态
private
void
SetTreeNodesStatus(TreeNodeCollection nodes)
{
foreach (TreeNode node in nodes)
{
if (NodesStatus[node.FullPath] != null )
{
node.Expand();
}
if (node.FullPath == SelectNodeFullPath)
{
treeView1.SelectedNode = node;
}
SetTreeNodesStatus(node.Nodes);
}
}
{
foreach (TreeNode node in nodes)
{
if (NodesStatus[node.FullPath] != null )
{
node.Expand();
}
if (node.FullPath == SelectNodeFullPath)
{
treeView1.SelectedNode = node;
}
SetTreeNodesStatus(node.Nodes);
}
}
下载: