简体   繁体   中英

how to get all selected checkboxes node name in TreeView using c# 4.0?

I have a TreeView with CheckBox in my C# Windows form based application.The user select an item by clicking the checkboxes in the nodes. Now i want to get the selected checkboxes node name whenever clicking getselectedlist button pressed by the user.how i do it?.

Please Guide me to get out of this issue...

You can just use simple recursive function:

List<String> CheckedNames( System.Windows.Forms.TreeNodeCollection theNodes)
{
    List<String> aResult = new List<String>();

    if ( theNodes != null )
    {
        foreach ( System.Windows.Forms.TreeNode aNode in theNodes )
        {
            if ( aNode.Checked )
            {
                aResult.Add( aNode.Text );
            }

            aResult.AddRange( CheckedNames( aNode.Nodes ) );
        }
    }

    return aResult;
}

Just use it on YourTreeView.Nodes

Or instead of recursively looping through every node in the TreeView every time something gets checked which could get expensive when, like me, you have hundreds or thousands of items in the list, but no more than 20 items being checked.

I add/remove from a string list after check/uncheck since I only needed the FullPath strings, but you could probably also use a collection of TreeNode in the same way if you needed that.

public partial class Form1 : Form
{
    List<String> CheckedNodes = new List<String>();

    public Form1()
    {
        InitializeComponent();
    }

    private void treeView1_AfterCheck(object sender, TreeViewEventArgs e)
    {
        if (e.Node.Checked)
        {
            CheckedNodes.Add(e.Node.FullPath.ToString());
        }
        else
        {
            CheckedNodes.Remove(e.Node.FullPath.ToString());
        }
    }
}
    //Uncomplicated, reliable method
    List<int> _valueList = new List<int>();
    private List<int> getCheckedNodes(TreeNodeCollection _parentNodeList)
    {
        foreach (TreeNode item in _parentNodeList)
        {
            if (item.Checked)
            {
                _valueList.Add(Convert.ToInt32(item.Value));
            }

            if (item.ChildNodes.Count > 0)
            {
                //.NET does not forget where it stayed.
                getCheckedNodes(item.ChildNodes);
            }
        } 

        return _valueList;
    }

On the button click event, you can iterate through whole tree as explained at http://msdn.microsoft.com/en-us/library/wwc698z7.aspx . Then for each TreeNode you can check if the checkbox is checked or not and if it is checked you can add its name in to a list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM