I need a treeview component with multipleselect. So I downloaded “C# TreeView with multiple selection“. Now I am having trouble removing items. The following code runs fine, but removes nothing:
private void removeToolStripMenuItem_Click(object sender, EventArgs e)
{
for (int i = 0; i < treeView1.SelectedNodes.Count; i++)
{
try
{
if (treeView1.Nodes[i].IsSelected)
{
treeView1.Nodes[i].Remove();
i--;
}
}
catch { }
}
treeView1.Update();
treeView1.Refresh();
}
treeView1.SelectedNodes.Remove();
Requires an object, but I don’t know which.
foreach (TreeNode tn in treeView1.SelectedNodes)
tn.Remove();
Throws an exception because the collection was modified.
Can someone help me out?
Thanks!
Try with a backward loop and use the Remove method on the Nodes collection passing the selected node
Also I don’t think you have to test if the node IsSelected because you are already using the SelectedNodes property. (Really I haven’t checked if this is the case with this customized treeview class, however the name suggest that the nodes included are already selected)