简体   繁体   English

检查组合框是否为空C#

[英]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. 我正在尝试使用Windows应用程序窗体中的C#检查组合框是否为空。 Below are two possible ways: 以下是两种可能的方法:

  1. if (string.IsNullOrEmpty(comboBox1.Text)) 如果(string.IsNullOrEmpty(comboBox1.Text))
  2. if (comboBox1.SelectedIndex == -1) 如果(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. 根据我的研究,第二种方法(如果(comboBox1.SelectedIndex == -1))将满足我的需求。 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 如果您只是要确保用户从可用列表中选择一项,只需将组合框的DropDownStyle更改为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 因此,如果test为假,则表示他们在可用项目列表中没有选择/输入的内容

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 )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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