[英]How do I check if selected value of the ListBox is not selected in C#?
此代碼將顯示從列表框中選擇的值。 例如,如果我賣出第1項,我將得到以下輸出: 您選擇了第1項 。
Label1.Text = "You have selected " + DropDownList1.SelectedValue + "<br />";
但是,如果我不選擇任何內容,然后單擊“提交”按鈕,則會得到: 您已選擇
我需要顯示為“您尚未選擇任何內容。請至少選擇一項。”
更新:我正在使用ASP.NET WebForms。
更新:
下面的答案實際上是不正確的(保留歷史記錄)。 一旦訪問SelectedIndex
屬性,則在未選擇任何內容的情況下,列表將立即使第一項處於選中狀態,並返回零。
因此,幾乎唯一剩下的選擇是在列表中的第一位有某種“虛擬物品”,並檢查SelectedIndex == 0
。
但是,以上內容僅適用於DropDownList
。 從ListControl
派生的其他控件(即ListBox
或RadioButtonList
)將正確顯示SelectedIndex == -1
。
這是不正確的答案 :
檢查SelectedIndex
屬性。 如果未選擇任何內容,則其值為-1。
if ( DropDownList1.SelectedIndex < 0 )
{
Label1.Text = "You have not selected anything";
}
else
{
Label1.Text = "You have selected " + DropDownList1.SelectedValue;
}
小心點!:
使用SelectedIndex屬性以編程方式指定或確定DropDownList控件中所選項目的索引。 始終在DropDownList控件中選擇一個項目 。 您不能同時清除列表中每個項目的選擇。
http://msdn.microsoft.com/zh-cn/library/system.web.ui.webcontrols.dropdownlist.selectedindex.aspx
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.