如何在C# Winforms中的按钮单击事件中获取组合框选定值?

4
我有一个下拉框,其中包含数字。我有一个按钮。我想获取下拉框的选定值。
我尝试了以下代码:
Messagebox.show("Selected value =="+cbWeeksFrom.SelectedValue);

输出

Selected value ==

我是winforms的新手。

更新

我尝试过了。

cbWeeksFrom.SelectedValue
cbWeeksFrom.Text
cbWeeksFrom.SelectedText
cbWeeksFrom.SelectedItem

它不起作用,甚至没有带来文本框的值。我认为它没有带来任何控件的值。


如果使用 cbWeeksFrom.SelectedIndex 会发生什么? - mjwills
5个回答

4

使用Combobox的.Text属性获取所选值,并使用.selectedindex查找是否选择了某个值。

if (cbWeeksFrom.SelectedIndex != -1)
        {                
            MessageBox.Show("Selected value == " + cbWeeksFrom.Text);
        }
        else
        {
            MessageBox.Show("please select a value");
        }

2

这取决于您如何向下拉框中添加项目。

SelectedValue仅在使用DataSource的情况下有效。

var numbers = new List<int> { 1, 2, 3, 4, 5 };
combobox.DataSource = numbers;

// on button click
MessageBox.Show($"Selected value is {combobox.SelectedValue}");

SelectedItem 应该在任何情况下都能正常工作,除非用户在组合框的可编辑部分输入了不存在于 combobox.Items 中的数字。

combobox.Items.AddRange(new object[] { 1, 2, 3, 4, 5});

// user input "7" in combobox
combobox.SelectedItem // will return null

SelectedText 是组合框中可编辑部分选定的文本。
请注意,如果 combobox.DropDownStyle = DropDownStyle.DropDownList,那么 combobox.SelectedText 将始终返回空字符串。


1
使用Combobox.Text或Combobox.SelectedItem属性。

你能否提供代码的其他部分来扩展你的问题? - esnezz

1
尝试这个:
ComboBoxItem current = (ComboBoxItem)cbWeeksFrom.SelectedItem;  
string item =current.Content.ToString();

0

简单易行的解决方案:

  string selectedValue = cbWeeksFrom.Text;
  Messagebox.show("Selected value == " + selectedValue);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接