ComboBox.SelectedText没有给我SelectedText

时间:2012-04-17 15:27:54

标签: c# winforms string combobox

我正在构建一个String,代码看起来像

String status = "The status of my combobox is " + comboBoxTest.SelectedText

我在VS2010中使用WinForm

结果如

  

“我的组合框的状态是”

11 个答案:

答案 0 :(得分:89)

我想你想用

String status = "The status of my combobox is " + comboBoxTest.Text

来自MSDN

的SelectedText属性
  

获取或设置在a的可编辑部分中选择的文本   组合框。

来自MSDN

的文字属性
  

获取或设置与此控件关联的文本。

答案 1 :(得分:16)

来自documentation

  

您可以使用SelectedText属性来检索或更改ComboBox控件中当前选定的文本。但是,您应该知道,由于用户交互,选择可以自动更改。例如,如果在按钮Click事件处理程序中检索SelectedText值,则该值将为空字符串。这是因为当输入焦点从组合框移动到按钮时,将自动清除选择。

     

当组合框失去焦点时,选择点将移动到文本的开头,并且任何选定的文本都将被取消选中。在这种情况下,获取SelectedText属性将检索空字符串,并设置SelectedText属性将指定的值添加到文本的开头。

答案 2 :(得分:9)

我认为您不需要SelectedText,但您可能需要

String status = "The status of my combobox is " + comboBoxTest.Text;

答案 3 :(得分:6)

我在5分钟前遇到这个问题。

我认为解决方案(使用visual studio 2005)是:

<script>
         $("input.<?php echo $ch_cnt; ?>").on('change', function (e) {
            if ($("input.<?php echo $ch_cnt; ?>:checked").length > 3) {
                $(this).prop('checked', false);
                alert("allowed only 3");
            }
        });
</script>

如果我错了,请原谅我。

答案 4 :(得分:4)

要获取所选项目,必须使用comboBox的SELECTEDITEM属性。由于这是一个Object,如果你想将它分配给一个字符串,你必须使用ToString()方法将它转换为字符串:

string myItem = comboBox1.SelectedItem.ToString(); //this does the trick

答案 5 :(得分:2)

以下是我将如何解决问题,假设您要更改say的文字,标签

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

答案 6 :(得分:2)

试试这个:

String status = "The status of my combobox is " + comboBoxTest.text;

答案 7 :(得分:0)

或尝试此代码

 String status = "The status of my combobox is " + comboBoxTest.SelectedItem.ToString();

答案 8 :(得分:0)

如果将Combobox绑定到KeyValuePair之类的东西,并在构造函数中使用如下属性:

 DataSource = dataSource,
 DisplayMember = "Value",
 ValueMember = "Key"

所以dataSource的类型为KeyValuePair ...

您最终不得不执行此操作...

  string v = ((KeyValuePair)((ComboBox)c).SelectedItem).Value;

(我有一个动态表格-c的类型为Control-因此必须将其转换为ComboBox)

答案 9 :(得分:0)

所有先前的答案都解释了OP“应该”做什么。我正在解释.SelectedText属性是什么。

.SelectedText属性不是combobox中的文本。突出显示该文本。它与.SelectedText的{​​{1}}属性相同。

下图显示textbox属性将等于“ ort”。

enter image description here

答案 10 :(得分:0)

如果您只想知道带有可编辑文本框(或 ComboBox 样式)的 ComboBoxStyle.DropDown 中的文本,您可以使用:

string str = comboBox.SelectedItem != null ?
                      comboBox.GetItemText(comboBox.SelectedItem) : comboBox.Text;
相关问题