Help with string comparison for C#

0 The Bullet · March 16, 2015
I am comparing string in Combobox for C# but how is it underlined green?

private void ambiance_ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
            if (ambiance_ComboBox1.SelectedItem == "Halt Attack Mode")

Here is the image:

Post a Reply


Oldest  Newest  Rating
+1 Eugene Botma · March 16, 2015
if you look at the datatype of the combobox.Items, you'll notice that it's a group of objects, not strings, so when you use ambiance_combobox.SelectedItem it returns an object. Now this object might or might not be a string. 

Generally they are strings, or the objects can be easily converted to a string using ToString(). So Tóth Bences answer should work in this case. An alternative is to use the SelectedText property.
0 The Bullet · March 17, 2015
I see, thanks for helping :D
0 Kuroodo Ditory · March 28, 2015
I know Java is similar to C# but I don't know if this works with C#.

Try doing ambiance_ComboBox1.SelectedItem.equals("Halt Attack Mode");
0 Eugene Botma · March 28, 2015
Both Mason Woods' and Kuroodo Ditorys suggestions should work ONLY IF the item is a string. If you assign another type of object to the list, these solutions will most probably cause a runtime error. Be mindful of the data types when using generic lists such as a listbox or combobox
0 Bill Harding · April 13, 2015
Mason Woods is correct. 
The SelectedItem property of Combo box is an object so you have to cast it before using it like a string 

public object SelectedItem { get;  set; }
    Member of System.Windows.Forms.ComboBox

The official example uses .ToString()

I do have one other suggestion:
Normally you would pull the SelectedItem out of the sender, not access it from the page's controls collection. 
Like this:

private void ambiance_ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
var cb= (ComboBox)sender;
if ((string)cb.SelectedItem == "Halt Attack Mode")
0 Sirajus Salekin · July 5, 2015

 instead of 

  • 1



C# is an object-oriented language designed for improving the development of web applications.