如何使用C#Winforms在按钮点击事件中获取组合框选择值?

时间:2017-08-19 11:15:44

标签: c# winforms combobox

我有一个有数字的组合框。我有一个按钮。我想获得组合框的选定值

我试过以下

Messagebox.show("Selected value =="+cbWeeksFrom.SelectedValue);

输出

Selected value ==

我是winforms的新手。

更新

我试过

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

它不能正常工作。甚至没有带来文本框值。我认为它没有带来任何控制值

5 个答案:

答案 0 :(得分:1)

使用Combobox.Text或Combobox.SelectedItem属性

答案 1 :(得分:1)

试试这个,

ComboBoxItem current = (ComboBoxItem)cbWeeksFrom.SelectedItem;  
string item =current.Content.ToString();

答案 2 :(得分:1)

使用Combobox的.Text属性来获取所选值并使用.selectedindex来查找某个值是否被选中

tr -d '\r' < infile > outfile

答案 3 :(得分:1)

这取决于您如何将项目添加到组合框中。

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将始终返回空字符串。

答案 4 :(得分:0)

简单易行的解决方案:

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