简体   繁体   中英

C#: If listbox string equals

how can I use an if statement like the following?:

 if ( listBox6.SelectedItem.ToString = ("hi")) 
{

}

I tried that and got the error:

Cannot assign to 'ToString' because it is a 'method group'

  1. Method invocations must have an argument list in parenthesis, even if the list is empty.

  2. The equality operator is == , not to be confused with the assignment operator = .

So your code should look like this:

if (listBox6.SelectedItem.ToString() == "hi")
{
}

Note that listBox6.SelectedItem returns null if there is no currently selected item. Invoking ToString in this case causes a NullReferenceException at runtime. It's probably safer to cast the selected item to string instead:

if ((string)listBox6.SelectedItem == "hi")
{
}

You made three mistake,:

1 . You forgot about parantessis of ToString() method.

2 . You try to make equality, in fact assigning value to method, should change = with == .

3 . You forgot null checking may be in future causes to problems.

you can edit it as below:

if ( listBox6.SelectedItem != null && listBox6.SelectedItem.ToString() == "hi")

Try:

if(listBox6.SelectedItem.ToString() == "hi") {
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM