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

与世无争的帅哥 提交于 2019-12-04 19:32:46

问题


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?


回答1:


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



回答2:


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



回答3:


You can use this:

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



回答4:


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.




回答5:


check the text property like this

if (combobox.text != String.Empty)
{
//continue
}
else
{
// error message
}



回答6:


if (cboDate.SelectedValue!=null)
{
      //there is a selected value in the combobox
}
else
{
     //no selected value
}



回答7:


if(combobox.Selectedindex==-1)
{
MessageBox.Show("Please Select an item");
}

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



回答8:


You can use SelectedIndex or SelectedItem properties of the ComboBox.




回答9:


Pl. note ComboBox.Text 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.

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.!
        }


来源:https://stackoverflow.com/questions/2460754/how-to-check-whether-the-item-in-the-combo-box-is-selected-or-not-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!