我正在构建一个字符串,代码如下:
String status = "The status of my combobox is " + comboBoxTest.SelectedText
我正在使用VS2010中的WinForm
结果看起来像:
"我的组合框的状态为"
根据文档:
你可以使用SelectedText属性来检索或更改ComboBox控件中当前选定的文本。但是,你需要知道由于用户交互而导致选择可以自动更改。例如,如果在按钮单击事件处理程序中检索SelectedText值,则该值将为空字符串。这是因为当输入焦点从组合框移动到按钮时,选择会自动清除。
当组合框失去焦点时,选择点移动到文本开头,并取消选择任何选定的文本。在这种情况下,获取SelectedText属性会检索一个空字符串,设置SelectedText属性会将指定的值添加到文本开头。
我在5分钟前遇到了这个问题。
我认为(使用Visual Studio 2005)的解决方法是:
myString = comboBoxTest.GetItemText(comboBoxTest.SelectedItem);
如果我错了,请原谅我。
我认为你不需要SelectedText
,但也许你需要
String status = "The status of my combobox is " + comboBoxTest.Text;
String status = "我的组合框状态是:" + comboBoxTest.text;
string myItem = comboBox1.SelectedItem.ToString(); //this does the trick
以下是我的解决方案,假设您想更改标签的文本:
private void comboBoxtest_SelectedIndexChanged(object sender, EventArgs e)
{
var combotext = comboBoxtest.Text;
var status = "The status of my combo box is" + combotext;
label1.Text = status;
}
DataSource = dataSource,
DisplayMember = "Value",
ValueMember = "Key"
所以dataSource
是键值对类型...
最终你需要做的是...
string v = ((KeyValuePair)((ComboBox)c).SelectedItem).Value;
我有一个动态表单 - 其中c
是Control
类型 - 所以必须将其转换为ComboBox。
最初的回答:
我有一个动态表单,其中 c 是 Control
类型,所以必须将其强制转换为ComboBox。
ComboBox
(或者ComboBoxStyle.DropDown
风格)中的文本,你可以使用以下代码:string str = comboBox.SelectedItem != null ?
comboBox.GetItemText(comboBox.SelectedItem) : comboBox.Text;