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>
- ListItem item = new ListItem("Select Item", "Select Item");
- DropDownList1.Items.Add(item);