Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

TreeNode.Remove() Bug??? 2

Status
Not open for further replies.

andegre

MIS
Oct 20, 2005
275
0
0
US
Hi All, I have a TreeView control that contains one parent node, then a very large directory structure beneath that. I've been working on this from a couple different ways.

First, I load the directory structure, and compare it to another one, if the files (and directories) are different, I add the node to the treeview. Once the list is generated, I make a second sweep through the files that are checked (if I'm showing ALL files, not just differences) with a 3rd party file comparison tool. With the results of that (and I have verified), if the files are truly the same, then I do a node.Remove(). That's where the problem occurs; first I was doing a foreach on the nodes, then removing them if they aren't checked. When a node gets removed, the machine loses the "ID" or the NEXT node that it was supposed to check (it successfully removes the desired node, but skips the check for the next one and goes to the third). I tried bypassing this by using a for loop instead but get the same results.

Then, I decided to wait until all the way done with the comparisons to do the node removal, and still have the same problem, although not as severe (it only leaves one or two nodes that should have been removed.

Has anyone seen anything like this/know of a tip/trick to get around this?

Thanks,
 
you cannot remove objects while iterating over a collection.
instead you need to put then items you want to remove into a separate collection and remove them.
Code:
var alphabet = new[] {a-z};
var remove_us = new List<string>();
foreach(var letter in alphabet)
{
  if(is_vowel(letter)) 
     remove_us.Add(letter);
}

foreach(var letter in remove_us)
{
   alphabet.Remove(letter);
}

return alphabet;
I would also recommend doing all this work before binding to the TreeView. The TreeView control should receive the final result.

using IEnumerable<> you can simplify the code.
Code:
public IEnumerable<FileInfo> get_relevant_files()
{
   foreach(var file in all_files)
   {
      if(should_be_displayed(file))
         yield return file;
   }
}

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
Yep. Cannot change the contents of a collection while iterating through them. Have to do it in two steps, or use an old-style for..next loop if the collection supports retrieving items by index.

Chip H.


____________________________________________________________________
www.chipholland.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top