heinst
heinst

Reputation: 8786

Know what option in combobox is selected in C#?

I have a combobox and have a list of things in it....the amount of things in the list is not set. It is gathering data from a folder and you can have an infinite (a little exaggeration) amount of items in the combobox...how do I know which option a user selects?

I tried the code below but it doesn't work. I'm brand new to C# and don't know what I'm doing wrong.

        comboBox1.SelectedIndex = 0;
        comboBox1.Refresh();

        if(comboBox1.SelectedIndex = 0)
        {
           //setting the path code goes here
        }

Upvotes: 2

Views: 1265

Answers (4)

General Grey
General Grey

Reputation: 3688

Edit: Apparently I was going for the quick answer instead of good information, I am adding more info to make this easier to read

There is an event for the combobox that fires everytime the selection changes. in the designer select your combobox, then the events tab and double click SelectionChanged.

if you simply need to access what has been selected from lets say a button click you can use as Rahul stated

Button1_Click(...)
{ 
    MessageBox.Show(comboBox1.SelectedItem.ToString()); 
}

or if you simply want to access the text that is currently displayed in the combobox

Button1_Click(...)
{ 
    MessageBox.Show(comboBox1.SelectedText); 
}

Upvotes: 2

YoryeNathan
YoryeNathan

Reputation: 14532

When you're using the = operator, it sets the right hand side into the left hand side, and the result is the right hand side (which also sets the left hand side).

When you're using the == operator, it checks whether the right hand side equals the left hand side, and the result is a bool (true/false).

int i = 10;
int j = 40;

Console.WriteLine(i == j); // false
Console.WriteLine(i); // 10
Console.WriteLine(j); // 40
Console.WriteLine(i = j); // 40
Console.WriteLine(i); // 40
Console.WriteLine(i == j); // true

So in the beginning, you are setting the SelectedIndex to 0, which you probably don't want to do, because you want to know which index is selected by the user.

So if you're changing the SelectedIndex, you won't be able to know what the user selected.

The condition you need is this:

if (comboBox1.SelectedIndex == 0)
{
    // Selected item is item 0
}

When you're doing this:

if (comboBox1.SelectedIndex = 0)
{
}

What actually happens is that SelectedIndex is set to 0, and then the compiler tries to cast 0 to a boolean (because it is inside an if condition), which will result with a compilation error.

Upvotes: 1

Rahul
Rahul

Reputation: 77926

Use ComboBox.SelectedItem Property.

Upvotes: 3

bjornruysen
bjornruysen

Reputation: 850

To compare values in C# you'll need to use "==" instead of "="

if(comboBox1.SelectedIndex == 0) 
{ 
   //setting the path code goes here 
} 

Upvotes: 5

Related Questions