Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

treeview

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...

like image 292
Saravanan Avatar asked May 11 '11 06:05

Saravanan


2 Answers

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

like image 97
Allender Avatar answered Oct 02 '22 05:10

Allender


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());
        }
    }
}
like image 23
Brett Wait Avatar answered Oct 02 '22 05:10

Brett Wait