0

Ok, so I want to be able to validate whether or not, male/female has been selected or if it hasn't been selected. Here's the code I have:

protected void checkGender()
    {
        var selectedGender = ddlGender.SelectedValue;

        if (selectedGender == "-1")
        {
            Label1.Text = "Please select your gender!";
        }
        else
        {
            Label1.Text = "";
        }
    }

<asp:DropDownList ID="ddlGender" runat="server">
  <asp:ListItem Value="-1">Please select...</asp:ListItem>
  <asp:ListItem Value="Male">Male</asp:ListItem>
  <asp:ListItem Value="Female">Female</asp:ListItem>
</asp:DropDownList>

2 Answers 2

2

I'd recommend to use RequiredFieldValidator rather than doing validation manually.

<asp:RequiredFieldValidator ID="rfvGender" runat="server"
     ControlToValidate="ddlGender"
     ErrorMessage="Please select your gender!"
     InitialValue="-1"> // Alternativaly you can set the InitialValue in Load event 
</asp:RequiredFieldValidator>

When using validator controls you can use the unified Page.IsValid property to check if your page is valid.

And in general it is better to use standard ASP.NET validation controls whenever possible otherwise you will end up with a pile of messy code which will be hard to maintain in future.

1
  • Actually this works great! I had the rfv but wanted to add some custome validation but this will work much better, I don't think there was a need for me or anyone to go to the bother of writing more code than you have to! Thanks @Alexander Manekovskiy
    – crsMC
    Mar 9, 2014 at 18:16
2

You can use SelectedIndex:

    var selectedGender = ddlGender.SelectedIndex;

    if (selectedGender == 0)
    {
        Label1.Text = "Please select your gender!";
    }
    else
    {
        Label1.Text = "";
    }
3
  • I think this is a good example of answer on the XY problem (meta.tex.stackexchange.com/a/2450). The author needs to validate the value in dropdown box but fails to do so and instead of pointing to the more canonical solution like standard asp.net validation controls author is given a workaround which of course solves the problem but is not giving the good guidance for future. So I doubt the value of this answer. Mar 9, 2014 at 18:19
  • Thanks for the feedback Alexander, both of these answers really helped me out!
    – crsMC
    Mar 9, 2014 at 18:24
  • @AlexanderManekovskiy you have a valid point, while it is true that ASP.NET has built in tools to achieve things. Sometimes you have to do things manually especially when you need to have more customization. for example if OP wanted to show a message box instead of a label. As the OP mention in his comments he wanted some custom stuff.
    – meda
    Mar 10, 2014 at 14:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.