简体   繁体   中英

How to check whether the item in the combo box is selected or not in C#?

I have a combo box in which I have to display the dates from a database. The user has to select a date from the combo box to proceed further, but I don't know how to make the user aware of selecting the item from the combo box first in order to proceed further.

What process should be followed so that a user can get a message if he has not selected the date from the combo?

if (string.IsNullOrEmpty(ComboBox.SelectedText)) 
{
 MessageBox.Show("Select a date");
}

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);
}

You can use this:

if (Convert.ToInt32(comboBox1.SelectedIndex) != -1)
{
    // checked
}
else
{
    // unckecked
}

You'll want to use DropDownStyle = DropDownList so you can easily make sure that the user picked an entry from the list and can't type random text in the box. Add an empty item to Items before you populate it (or "Please select"). Now, the default is automatically empty and the test is simple: just check that SelectedIndex > 0.

check the text property like this

if (combobox.text != String.Empty)
{
//continue
}
else
{
// error message
}
if (cboDate.SelectedValue!=null)
{
      //there is a selected value in the combobox
}
else
{
     //no selected value
}
if(combobox.Selectedindex==-1)
{
MessageBox.Show("Please Select an item");
}

else
{
MessageBox.Show("An Item was selected");
}

Pl. note only checks for the Text that is at the editable region of the ComboBox, so that's not supposed to be used when you want to check if there's some selection from within the ComboBox. 只检查可编辑区域的Text,因此当您想要检查ComboBox中是否有一些选择时,不应该使用它。

This will work always.

        int a = ComboBox.SelectedIndex.CompareTo(-1);

        if (a == 0)
        {
            MessageBox.Show("Please select something.");
        }
        else
        {
            // do something if combo box selection is done.!
        }

您可以使用ComboBox SelectedIndexSelectedItem属性。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM