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. E.g. if I sellect Item 1 I will get the followi开发者_如何转开发ng output: You have selected Item 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.
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.
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
.
The above, however, is only true for DropDownList
. Other controls derived from ListControl
(i.e. ListBox
or RadioButtonList
) will correctly show SelectedIndex == -1
.
Here goes the incorrect answer:
Check the SelectedIndex
property. If nothing is selected, it will have the value of -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. An item is always selected in the DropDownList control. 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
精彩评论