Gil Peretz
Gil Peretz

Reputation: 2419

how to check if item is selected from a comboBox in C#

I'm pretty new here.

I have a form, and want to check if the user filled it in correctly. In the form there's a combo box; how can I build the "if" statement for checking whether the user picked an item from it ?

P.S. Sorry for my bad English, it's not my mother tongue. :)

Upvotes: 26

Views: 164258

Answers (7)

Joe Carter
Joe Carter

Reputation: 59

I've found that using this null comparison works well:

if (Combobox.SelectedItem != null){
   //Do something
}
else{
  MessageBox.show("Please select a item");
}

This will only accept the selected item and no other value which may have been entered manually by the user which could cause validation issues.

Upvotes: 0

petey m
petey m

Reputation: 365

You can try

if(combo1.Text == "")
{

}

Upvotes: 0

Roy T.
Roy T.

Reputation: 9638

Use:

if(comboBox.SelectedIndex > -1) //somthing was selected

To get the selected item you do:

Item m = comboBox.Items[comboBox.SelectedIndex];

As Matthew correctly states, to get the selected item you could also do

Item m = comboBox.SelectedItem;

Upvotes: 77

Gokul
Gokul

Reputation: 137

Here is the perfect coding which checks whether the Combo Box Item is Selected or not

if (string.IsNullOrEmpty(comboBox1.Text))
{
    MessageBox.Show("No Item is Selected"); 
}
else
{
    MessageBox.Show("Item Selected is:" + comboBox1.Text);
}

Upvotes: 7

Vignesh B
Vignesh B

Reputation: 45

if (comboBox1.SelectedIndex == -1)
{
    //Done
}

It Works,, Try it

Upvotes: 2

Nighil
Nighil

Reputation: 4129

if (combo1.SelectedIndex > -1)
{
    // do something
}

if any item is selected selected index will be greater than -1

Upvotes: 1

user203570
user203570

Reputation:

You seem to be using Windows Forms. Look at the SelectedIndex or SelectedItem properties.

if (this.combo1.SelectedItem == MY_OBJECT)
{
    // do stuff
}

Upvotes: 5

Related Questions