Monday, June 1, 2009

Dropdownlist selected item validation fails: the suggestion

Today I got across a question in the asp.net forum which seems simple but is still confusing for many beginners. So I am giving a place for it here:

Question:

Hi Everyone,

I'm trying to set some error handling by returning a message when a button is clicked and the user has not selected an item from the dropdown menu. I'm using this but for some reason it is being ignored?

protected void validatebtn_Click(object sender, ImageClickEventArgs e)
{
if (!(DropDownList1.SelectedValue == "Select Item"))
{
lblerrors.Text = "
You have not selected an item from the drop down list.";
}
else
{
//...continue with the code.
}
}

When I debug the code, it reads the first line:

if (!(DropDownList1.SelectedValue == "Select Item"))
and then skips to the else statement and misses my message?

Can anyone advise why this is happening?

Thanks.
Chloe ~X~

Among other suggestions, here is what I have suggested:

Answer:

Looking into your explanation and reading all the answers given by members, some questions came in my mind.

1. Did you check what value is exactly selected from the dropdownlist? I mean DropDownList1.SelectedValue should be "Select Item" only then your comparision will be true.
2. Are you adding this "Select Item" from design view or is it added programmatically from code behind? Did you only specify "text" or both text and value? See the markup below:

<asp:DropDownList ID="ddlTest" runat="server">
<asp:ListItem Text="Select Item" Value="Select Item" Selected="True"></asp:ListItem>
</asp:DropDownList>

If you don't put Selected="true", this item may display at the first position, but is not selected yet. So don't forget to set this. Another thing to notice is you should have set both Text and Value. The "SelectedValue" corresponds to the "Value" in the markup. Only then your code will work. Don't forget to have both text and value if you add listitem to the dropdownlist from codebehind, like this one:

ListItem item = new ListItem("Select Item", "Select Item");
DropDownList1.Items.Add(item);

Hope this helps. Please feel free to ask if the problem persists or if further help is required. Thanks.

kick it on DotNetKicks.com Shout it pimp it

1 comments:

Lee Dumond said...

This is NOT the preferred way to validate whether a selection has been made in a dropdown list. You can use the RequiredFieldValidator for dropdown lists, which is much easier and even works on the client side.

Post a Comment

Hope you liked this post. You can leave your message or you can put your valuable suggestions on this post here. Thanks for the sharing and cooperation!

Popular Posts

Recent Articles