简体   繁体   中英

Validating a Drop Down List in asp.net using c#?

I have a drop down list on a page, by default the option that is displayed is 'Please Select One'.At the moment users can select that option and gain access to the next page, what I want to do is if 'Please Select One' is selected ensure that access to the next page/step will not be given until an actual option on the drop down list is selected.

Im guessing some sort of If statement but im unsure of how to do this.

Any help would be great.

This is my code for my ddl

 <td class="question">
     Out of Hours Working:
 </td>
 <td>
    <asp:DropDownList ID="ddlout" runat="server" Width="150px">
      <asp:ListItem Text="Please Select One"></asp:ListItem>
      <asp:ListItem Text="Yes"></asp:ListItem>
      <asp:ListItem Text="No"></asp:ListItem>
    </asp:DropDownList>
    <span class="mandatory">*</span>
    <asp:RequiredFieldValidator
        ID="RequiredFieldValidator14" runat="server" ControlToValidate="ddlout"
        ErrorMessage=" Required." InitialValue="Please select one..."
        ForeColor="Red" SetFocusOnError="true"></asp:RequiredFieldValidator>
 </td>

Instead of using the <asp:RequiredFieldValidator> use the <asp:CompareValidator> ...

<asp:CompareValidator
    ID="val14" runat="server" ControlToValidate="ddlout"
    ErrorMessage=" Required." Operator="NotEqual"
    ValueToCompare="Please Select One"
    ForeColor="Red" SetFocusOnError="true" />

Note the additional Operator and ValueToCompare . If the value of the dropdown is "not equal" to the "value to compare" then it is ok - otherwise it will fire.

See MSDN for more information

I would, however, recommend that you give actual Value 's to each of the ListItem objects, rather than using the Text alone. For instance <asp:ListItem value="0" Text="Please Select One"/> which you can then test ValueToCompare="0"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM