views:

320

answers:

3

Hello, i have this code:

Nodo N;  
        foreach (string S in listBox_nodos.Items)  
        {  
            N = graph.getNodoName(S);  
            string comp = (string) listBox_nodos.SelectedItem;  
            if (comp == S)  
               System.Console.WriteLine(N.NAME);  
        }  

I get InvalidOperationException and the application crashes.
Cant get why. Any help? thanks

EDIT: The 'N.NAME' prints! And then goes the crash.
EDIT2: I've tried to catch the Exception, the application crashes anyway

+1  A: 

At which line do you get the exception? Without knowing what datatype listBox_nodos has, my first guess w2ould be that Items does not contain a lot of strings, but rather ListBoxItems

foreach (var item in listBox_nodos.Items)  
{  
    N = graph.getNodoName(item.Value); // or .SomethingElse
David Hedlund
When i add items to the listbox, they are strings. I guess i have to learn more about listbox's.
Ricardo
Problem solved. I changed listBox_nodos.Items to listBox_nodos.SelectedItems. But still, i cant get the reason for the Exception
Ricardo
The foreach loop throws this exception when you modify the Items collection inside the loop. Using SelectedItems instead could indeed avoid that, as long as you don't change the selected items.
Hans Passant
@nobugz Thanks, now i got the reason for the Exception.
Ricardo
A: 

Perhaps the SelectedItem property isn't a string. Try using ToString() on it instead of casting and see if that solves your problem (or cast to the actual type and compare).

tvanfosson
Did that. Exactly the same Exception
Ricardo
+1  A: 
  • as mentioned before, the full exception would be nice to see (if in the VS debugger, you can get it from the exception helper dialog or the $exception entry in Debug -> Windows -> Locals). Worst-case you should be able to try { .. } catch (Exception ex) { System.Console.WriteLine(ex); (Exception's ToString includes the stack trace)

    • if you're not sure of the types involved, could get the Items/SelectedItem as IEnumerable/object and then gettype() on them and display that.
  • when trying to display things, may also want to try MessageBox.Show just in case the exception is coming from the use of Console for some reason.

  • unrelated to the exception, but it looks like you're interating over the listbox items to find the selected item - if that's true, why not just use the selected item directly?

James Manning
Thanks for your time! Yes, indeed. I cant put the info here now cus my application has advanced, and the code is completely different. I wasn't using the item directly because the ListBox was just a string Collection that represented an ArrayList of objects. I'm student and this site and comments are helping me very much, thanks for the time really.
Ricardo