Know what option in combobox is selected in C#?

筅森魡賤 提交于 2019-12-24 01:54:31

问题


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
        }

回答1:


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); 
}



回答2:


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

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



回答3:


Use ComboBox.SelectedItem Property.




回答4:


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.



来源:https://stackoverflow.com/questions/10517640/know-what-option-in-combobox-is-selected-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!