Hello. How to fix the error in the code?

foreach (TreeViewItem objTreeviewItem in tv.Items) { foreach (TreeViewItem objTre in objTreeviewItem.Items) { if (objTre.Header.Equals(textTitle.Text)) { objTre.IsSelected = true; s = objTreeviewItem.Items.IndexOf(tm); current = s; vit = objTreeviewItem as TreeViewItem; } } } 
  • s - string, not? - GanjaBoss
  • No error shows here foreach (TreeViewItem objTreeviewItem in tv.Items) - Demon

2 answers 2

In the above code, there is no fragment where the collection is filled. Perhaps, indeed, the ItemsCollection contains objects of type String , and not of type TreeViewItem ?

  • The collection is filled with this before in the other method tv.Items.Add (new TreeViewItem ()). And how do I convert it correctly to TreeViewItem. - Demon
  • So in cycles and there should be ItemsCollection or not? How can I get parent and child items treeView in a loop differently? - Demon
  • I suggested that you do step by step debugging and use the undefined type var. Do this, set the breakpoint in the foreach loop and there you can see what type this variable will accept. Here it is and use it (it is undesirable to use var in general in c #, but it will do for debugging) - Olter
 foreach (var objTreeviewItem in tv.Items) 

This is harsh, but the problem should be solved :)

  • In general, I have a bad suspicion that objTreeviewItem.Items is of type ItemCollection and not TreeViewItem. Better check through step by step debugging. - Olter