what i am trying to do is check whether an item in a list box is selected.

The method is being run on a separate thread so i would need to use a method invoker i believe.

string list = "";
lbxList.Invoke(new MethodInvoker(delegate { list = lbxList.SelectedItem.ToString(); }));

if (list != null)
{
 //do something
}

this code will blow up if the selected item is null because the string list wont hold it, so i would need a way to combine the top 2 lines into an if statement checking for null.

Thanks

有帮助吗?

解决方案

This should do:

string list = "";
lbxList.Invoke(new MethodInvoker(delegate
{
    if (lbxList.SelectedItem != null)
        list = lbxList.SelectedItem.ToString();
}));

//do something

Just place the if-statement inside the anonymous method.

Note that .ToString is highly unlikely to ever return null for anything, the documentation of object.ToString states that overriding types should implement the method to return a meaningful value. Since we already know that .SelectedItem is not null, checking for null is not really necessary. You can leave it in if you really want, but if you're afraid that .ToString should return null, I would instead change the code to this:

string list = "";
lbxList.Invoke(new MethodInvoker(delegate
{
    if (lbxList.SelectedItem != null)
        list = lbxList.SelectedItem.ToString() ?? string.Empty;
}));

//do something
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top