开发者

C# InvalidOperationException

开发者 https://www.devze.com 2022-12-15 12:18 出处:网络
Nodo N; foreach (string S in listBox_nodos.Items) { N = graph.getNodoName(S); string comp = (string) listBox_nodos.SelectedItem;
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 Invalid开发者_高级运维OperationException and the application crashes.

Can't 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.


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


  • 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?


I have had a similar problem before, also related to selected items. I investigated it extensively and was not able to find a fix. I eventually wound up remaking the form (though I think just the control was necessary) and that seemed to fix it.

0

精彩评论

暂无评论...
验证码 换一张
取 消