Windows窗体中把TreeView选中的值,添加到ListBox中

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();

 

转载于:https://www.cnblogs.com/wenjie/archive/2010/10/29/1864401.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值