1: TreeView中2層資料,父節點選中後,自動選中所有子節點
2:把第二層資料添加到 ListBox中
3:如果資料已經在ListBox中存在,則不添加
4:可以刪除ListBox中選中資料
類:TreeViewCheck 用於實現父節點選中後,自動選中所有子節點
代碼
1 public static class TreeViewCheck
2 {
3 /// <summary>
4 /// 系列節點 Checked 屬性控制
5 /// </summary>
6 /// <param name="e"></param>
7 public static void CheckControl(TreeViewEventArgs e)
8 {
9 if (e.Action != TreeViewAction.Unknown)
10 {
11 if (e.Node != null)
12 {
13 CheckParentNode(e.Node, e.Node.Checked);
14 }
15 if (e.Node.Nodes.Count > 0)
16 {
17 CheckAllChildNodes(e.Node, e.Node.Checked);
18 }
19 }
20 }
21 #region 私人方法
22 //改變所有子節點的狀態
23 private static void CheckAllChildNodes(TreeNode pn, bool IsChecked)
24 {
25 foreach (TreeNode tn in pn.Nodes)
26 {
27 tn.Checked = IsChecked;
28 if (tn.Nodes.Count > 0)
29 {
30 CheckAllChildNodes(tn, IsChecked);
31 }
32 }
33 }
34 //改變父節點的選中狀態
35 private static void CheckParentNode(TreeNode curNode, bool IsChecked)
36 {
37 bool bChecked = true;
38 if (curNode.Parent != null)
39 {
40 foreach (TreeNode node in curNode.Parent.Nodes)
41 {
42 if (node.Checked == false)
43 {
44 bChecked = false;
45 break;
46 }
47 }
48 if (bChecked)
49 {
50 curNode.Parent.Checked = true;
51 CheckParentNode(curNode.Parent, true);
52 }
53 else
54 {
55 curNode.Parent.Checked = false;
56 CheckParentNode(curNode.Parent, false);
57 }
58 }
59 }
60 #endregion
61 }
TreeView中選中或取消節點觸發:
private void treeView1_AfterCheck(object sender, TreeViewEventArgs e)
{
TreeViewCheck.CheckControl(e);
}
添加TreeView中選中項的值到listBox中
代碼
private void button1_Click(object sender, EventArgs e)
{
foreach (TreeNode node in treeView1.Nodes)
{
foreach (TreeNode nd in node.Nodes)
{
if (nd.Checked)
{
if (VerifyNotExist(nd.Text))
{
listBox1.Items.Add(nd.Text);
}
}
}
}
}
public bool VerifyNotExist(string theNodeText)
{
//便利listBox1中的項目,如果已經存在,返回False
for (int i = 0; i < listBox1.Items.Count; i++)
{
if (theNodeText == listBox1.Items[i].ToString())
{
return false;
}
}
//如果不存在,返回True
return true;
}
//刪除選中項
代碼
//ListBox.SelectedIndexCollection indices = listBox1.SelectedIndices;
// int count = indices.Count;
// listBox1.BeginUpdate();
// for (int i = 0; count != 0; i++)
// {
// listBox1.Items.RemoveAt(indices[0]);
// count--;
// }
//listBox1.EndUpdate();
while (listBox1.SelectedIndex != -1)
{
listBox1.Items.Remove(listBox1.SelectedItem);
}
刪除ListBox中所有項
listBox1.Items.Clear();