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());
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With