最近项目里用到treeview,原先设计的是一开始就把所有数据都加载到treeview里,后来发现客户的数据量实在太大,加载所有数据要2分钟,这个是客户没法接受的。后来就考虑到用户也不是一开始就要看所有的数据,用户也是一层一层地展开,所以我们就考虑是不是可以实现以当用户展开某个结点时才加载当前结点下面的数据。一番查找后,发现treeview有BeforeExpand事件可以实现我们的需求。
下面介绍具体的实现代码:
1. 首先只加载各部门(结点)的信息
monospace; margin: 0em; width: 100%; background-color: #fbfbfb"> 1: List<string> m_Departments = new List<string>() { "湖北.黄石", "湖北.鄂州", "湖北.武汉" };2: private void AddDepartMents(List<string> departments)3: {4: if (m_Root == null)
5: {6: var root = departments[0].Split('.')[0];
7: m_Root = new TreeNode(root);
8: m_Root.Tag = root;9: treeView1.Nodes.Add(m_Root);10: }11:12:13: foreach (var department in departments)
14: {15: var parent = m_Root;16: var dts = department.Split('.');
17: for (int i = 1; i < dts.Length; i++)
18: {19: if (!m_OrgNodeManager.ContainsKey(dts[i]))
20: {21: var child = new TreeNode(dts[i],1,1);
22: child.Tag = dts[i];23: child.ToolTipText = department;24: m_OrgNodeManager.Add(dts[i], child);25: parent.Nodes.Add(child);26: parent = child;27: }28: }29:30: parent.Nodes.Add("");31: }32: }
这里要注意,每个结点加完后,要加上一个空的子结点parent.Nodes.Add(""); 不然就没有那个加号让你点了。
2. 实现BeforeExpand事件
1: private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)2: {3: TreeNode curentNode = e.Node;4: if (curentNode.ImageIndex == 1)
5: {6: curentNode.Nodes.Clear();7: foreach (var user in m_UserManager)
8: {9: if (user.Value.ToString() == curentNode.ToolTipText.ToString())
10: {11: TreeNode userNode = new TreeNode(user.Key);
12: curentNode.Nodes.Add(userNode);13: }14: }15: }16: }