Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get combo box selected value in button click event using C# Winforms?

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

like image 362
Liam neesan Avatar asked Oct 12 '25 14:10

Liam neesan


2 Answers

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");
        }
like image 131
santosh Avatar answered Oct 14 '25 06:10

santosh


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.

like image 35
Fabio Avatar answered Oct 14 '25 05:10

Fabio