C# 获取组合框设置值作为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13791891/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:48:22  来源:igfitidea点击:

Get combobox set value as string

c#combobox

提问by Marek Buchtela

Found several ways to do so, but none of them works for me.. I have a combobox with variable number of options (taken from dynamic xml file). For next, I need to know what the user choosed, and I cant find out how to do it. This is one of ways I found and tried:

找到了几种方法,但它们都不适合我。我有一个带有可变数量选项的组合框(取自动态 xml 文件)。接下来,我需要知道用户选择了什么,但我不知道如何去做。这是我发现并尝试过的方法之一:

string myString = myCombobox.SelectedValue.ToString();

At least I dont get an error, but when I try to show that string, it does nothing.

至少我没有收到错误消息,但是当我尝试显示该字符串时,它什么也没做。

回答by adripanico

Try with myCombobox.SelectedValue.Value.ToString()or myCombobox.SelectedValue.Text.ToString(). Anyway, this question is too low quality for this forum. You need to do some research before asking. That's why I'm voting down you.

尝试使用myCombobox.SelectedValue.Value.ToString()myCombobox.SelectedValue.Text.ToString()。无论如何,这个问题对于这个论坛来说质量太低了。在问之前你需要做一些研究。这就是我投票否决你的原因。

回答by Vlad

try myCombobox.SelectedItem.ToString();

试试 myCombobox.SelectedItem.ToString();

it will work if you are adding items to the combobox using this way:

如果您使用这种方式将项目添加到组合框,它将起作用:

  comboBox1.Items.Add("Item");

e.g.

例如

        myComboBox.Items.Add("Item1");
        myComboBox.Items.Add("Item2");
        myComboBox.Items.Add("Item3");

        myComboBox.SelectedIndex = 1; //force change selection
        Console.WriteLine(myComboBox.SelectedItem.ToString()); //will output Item2

回答by bigcakes

string myString = myCombobox.Text;

回答by Andrej Lucansky

myCombobox.SelectedItem.ToString(); 

should do the trick for you.

应该为你做的伎俩。

回答by mangatinanda

Had a similar problem, try this:

有类似的问题,试试这个:

string myString = ((ComboBoxItem)myCombobox.SelectedItem).Content.ToString();

It works for me!

这个对我有用!

Just try to understand seeing myComboboxdesign.

试着理解看myCombobox设计。

回答by PasinduM

Use mycombobox.SelectedItem.ToString();Instead of the SelectedValue

使用mycombobox.SelectedItem.ToString();代替SelectedValue