[英]How to check whether the item in the combo box is selected or not in C#?
我有一个组合框,我必须在其中显示数据库中的日期。 用户必须从组合框中选择日期以继续进行,但我不知道如何让用户首先从组合框中选择项目以便继续进行。
应该遵循什么过程,以便用户可以在未从组合中选择日期时收到消息?
if (string.IsNullOrEmpty(ComboBox.SelectedText))
{
MessageBox.Show("Select a date");
}
这是一个完美的编码,用于检查是否选择了组合框项目:
if (string.IsNullOrEmpty(comboBox1.Text))
{
MessageBox.Show("No Item is Selected");
}
else
{
MessageBox.Show("Item Selected is:" + comboBox1.Text);
}
你可以用这个:
if (Convert.ToInt32(comboBox1.SelectedIndex) != -1)
{
// checked
}
else
{
// unckecked
}
您将需要使用DropDownStyle = DropDownList,以便您可以轻松确保用户从列表中选择了一个条目,并且无法在框中键入随机文本。 在填充项目之前向项目添加空项目(或“请选择”)。 现在,默认值自动为空,测试很简单:只需检查SelectedIndex> 0。
像这样检查text属性
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。 注意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.!
}
您可以使用ComboBox
SelectedIndex
或SelectedItem属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.