Reputation: 2571
I have a combo box which has numbers. I have a button. I wants to get the selected value of combo box
I tried like below
Messagebox.show("Selected value =="+cbWeeksFrom.SelectedValue);
Output
Selected value ==
I am new to winforms.
Update
I tried
cbWeeksFrom.SelectedValue
cbWeeksFrom.Text
cbWeeksFrom.SelectedText
cbWeeksFrom.SelectedItem
it's not working. Not even bringing textbox value. I think it's not bringing any control values
Upvotes: 4
Views: 8366
Reputation: 32443
It is depend on how you added items to the combobox.
SelectedValue will work only in cases when DataSource
was used
var numbers = new List<int> { 1, 2, 3, 4, 5 };
combobox.DataSource = numbers;
// on button click
MessageBox.Show($"Selected value is {combobox.SelectedValue}");
SelectedItem should work in any cases, except in situation where user input number(in editable part of combobox) which not exists in the combobox.Items
combobox.Items.AddRange(new object[] { 1, 2, 3, 4, 5});
// user input "7" in combobox
combobox.SelectedItem // will return null
SelectedText is selected text in editable part of combobox.
Notice that if combobox.DropDownStyle = DropDownStyle.DropDownList
then combobox.SelectedText
will always return empty string.
Upvotes: 2
Reputation: 377
use .Text property of Combobox to get selected value and use .selectedindex to find some value is selected or not
if (cbWeeksFrom.SelectedIndex != -1)
{
MessageBox.Show("Selected value == " + cbWeeksFrom.Text);
}
else
{
MessageBox.Show("please select a value");
}
Upvotes: 4
Reputation: 222722
Try this,
ComboBoxItem current = (ComboBoxItem)cbWeeksFrom.SelectedItem;
string item =current.Content.ToString();
Upvotes: 1
Reputation: 2275
Simple and easy solution :
string selectedValue = cbWeeksFrom.Text;
Messagebox.show("Selected value == " + selectedValue);
Upvotes: 0