如何在C#中检查组合框中的项目是否被选中?

时间:2010-03-17 08:35:22

标签: c# .net combobox selecteditem

我有一个组合框,我必须在其中显示数据库中的日期。用户必须从组合框中选择一个日期才能继续,但我不知道如何让用户首先从组合框中选择项目以便继续进行。

应该遵循哪个流程,以便用户在未从组合中选择日期时收到消息?

9 个答案:

答案 0 :(得分:12)

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

答案 1 :(得分:4)

这是一个完美的编码,用于检查是否选择了组合框项目:

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

答案 2 :(得分:3)

您可以使用:

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

答案 3 :(得分:2)

您将需要使用DropDownStyle = DropDownList,以便您可以轻松确保用户从列表中选择了一个条目,并且无法在框中键入随机文本。在填充项目之前向项目添加空项目(或“请选择”)。现在,默认值自动为空,测试很简单:只需检查SelectedIndex> 0

答案 4 :(得分:1)

像这样检查文本属性

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

答案 5 :(得分:1)

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

答案 6 :(得分:1)

user_a = "No selection"
def if_statement():
    global user_a # here is the trick ;-)
    user_choice = raw_input("Pick 1 or 2\n")
    if user_choice == "1":
        user_a = input("What would you like A to equal?\n")
        if_statement()
    elif user_choice == "2":
        print("A equals: " + user_a)
        if_statement()

if_statement()

答案 7 :(得分:0)

您可以使用SelectedIndex的{​​{1}}或SelectedItem属性。

答案 8 :(得分:0)

PL。 note ComboBox.Text 仅检查ComboBox可编辑区域的Text,因此当您想要检查ComboBox中是否有一些选择时,不应该使用它。

这将始终有效。

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

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