简体   繁体   English

如何检查C#中未选择ListBox的选定值?

[英]How do I check if selected value of the ListBox is not selected in C#?

This code will display the selected value from the listbox. 此代码将显示从列表框中选择的值。 Eg if I sellect Item 1 I will get the following output: You have selected Item 1 . 例如,如果我卖出第1项,我将得到以下输出: 您选择了第1项

Label1.Text = "You have selected " + DropDownList1.SelectedValue + "<br />";

But if I don't select anything and click on Submit button, I will get: You have selected 但是,如果我不选择任何内容,然后单击“提交”按钮,则会得到: 您已选择

What would I need to make it display "You have not selected anything. Please select at least 1 item." 我需要显示为“您尚未选择任何内容。请至少选择一项。”

UPDATE: I am using ASP.NET WebForms. 更新:我正在使用ASP.NET WebForms。

Update: 更新:
The below answer is actually incorrect (left for history). 下面的答案实际上是不正确的(保留历史记录)。 Once you access the SelectedIndex property, when nothing is selected, the list will immediately make the first item selected, and return zero. 一旦访问SelectedIndex属性,则在未选择任何内容的情况下,列表将立即使第一项处于选中状态,并返回零。

So pretty much the only choice that remains is to have some kind of "dummy item" very first in the list, and check for SelectedIndex == 0 . 因此,几乎唯一剩下的选择是在列表中的第一位有某种“虚拟物品”,并检查SelectedIndex == 0

The above, however, is only true for DropDownList . 但是,以上内容仅适用于DropDownList Other controls derived from ListControl (ie ListBox or RadioButtonList ) will correctly show SelectedIndex == -1 . ListControl派生的其他控件(即ListBoxRadioButtonList )将正确显示SelectedIndex == -1

Here goes the incorrect answer : 这是不正确的答案
Check the SelectedIndex property. 检查SelectedIndex属性。 If nothing is selected, it will have the value of -1. 如果未选择任何内容,则其值为-1。

if ( DropDownList1.SelectedIndex < 0 )
{
    Label1.Text = "You have not selected anything";
}
else
{
    Label1.Text = "You have selected " + DropDownList1.SelectedValue;
}

Be carefull!: 小心点!:

Use the SelectedIndex property to programmatically specify or determine the index of the selected item from the DropDownList control. 使用SelectedIndex属性以编程方式指定或确定DropDownList控件中所选项目的索引。 An item is always selected in the DropDownList control . 始终在DropDownList控件中选择一个项目 You cannot clear the selection from every item in the list at the same time. 您不能同时清除列表中每个项目的选择。

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.dropdownlist.selectedindex.aspx http://msdn.microsoft.com/zh-cn/library/system.web.ui.webcontrols.dropdownlist.selectedindex.aspx

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

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