简体   繁体   中英

Check if Combo box is empty C#

I am trying to check if a combo box is empty using C# in a Windows Application Form. Below are two possible ways:

  1. if (string.IsNullOrEmpty(comboBox1.Text))
  2. if (comboBox1.SelectedIndex == -1)

In order to ensure that the user would ONLY select a value from the drop down and NOT write it s own answer, which is the best approach? From my research the second method (if (comboBox1.SelectedIndex == -1)) will satisfy my needs. Am l right?

If your concern is only making sure that users choose an item from the list available, simply change your combobox's DropDownStyle to DropDownList

or if you want to allow them to type but then ensure it is on the list, you can do something like this:

var txt = comboBox1.Text;

if(string.IsNullOrEmpty())
  return;

var test = comboBox1.Items?.OfType<string>().ToList().Any(x => x?.Trim() == txt?.Trim());

so if test is false, it means what they have selected/typed does not exist in list of available items

for combobox you can use this code below to check if it's empty or not

 if(comboBox1.Items.Count == 0 )
 {
    // your code
 }

This is what i try and it 's work. Feel free to comment:

if (comboBox1.SelectedIndex > -1 )

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