views:

103

answers:

2

This code will display the selected value from the listbox. E.g. if I sellect Item 1 I will get the following 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.

+1  A: 

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;
}
Fyodor Soikin
Oh there you go. So it has to be less than 0. I've tried with 0, and with null but it didn't work. Thanks!
Silence of 2012
@Sahat: This answer is actually incorrect, as I have just found by looking in Reflector. Please see my update for correct answer.
Fyodor Soikin
I see what you mean Fyodor, but it works here with the code that you've posted the first time. It show You have not selected anything, just as I want it to be. Perhaps it's the new feature of ASP.NET 4.0?
Silence of 2012
Well, I'm actually looking at ASP.NET 4.0 as well. Maybe you have some other kind of control, not the `DropDownList`?
Fyodor Soikin
I think I've confused everyone including myself by using ListBox control named DropDownList1. It is ListBox which is why it probably lets me use that code.
Silence of 2012
+1  A: 

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

Markust