简体   繁体   中英

How to make required field validator on dropdownlist?

I have a dropdownlist where I added an extra value to (Choose channel...). If this value is selected I want a message displayed that is required, what I tried is:

<td>
    <asp:DropDownList ID="ServiceChannelDropDownList" AppendDataBoundItems="true"
    runat="server" DataTextField="Description" DataValueField="ID">
   <asp:ListItem Value="-1" Text="Choose channel..." />
   </asp:DropDownList>
   <asp:RequiredFieldValidator ID="DropDownListRequiredFieldValidator" runat="server"
                                ControlToValidate="ServiceChannelDropDownList" 
                                InitialValue="-1"
                                ErrorMessage="*"                                 
    </asp:RequiredFieldValidator>
</td>

Unfortunately this just let me select the initial value (which naturally does not exist in the database) without saying it is not allowed. How to solve this?

You need to add the default value in your code behind(.cs) where you bind Dropdownlist data, instead of doing it in .aspx page

ServiceChannelDropDownList.DataBind();
ServiceChannelDropDownList.Items.Insert(0, new ListItem("Choose channel...","-1"));
<td>
    <asp:DropDownList ID="ServiceChannelDropDownList" AppendDataBoundItems="true"
    runat="server" DataTextField="Description" DataValueField="ID">
   <asp:ListItem Value="0" Text="Choose channel..." />
   </asp:DropDownList>
   <asp:RequiredFieldValidator ID="DropDownListRequiredFieldValidator" runat="server"
                                ControlToValidate="ServiceChannelDropDownList" 
                                InitialValue="0"
                                ErrorMessage="*"                                 
    </asp:RequiredFieldValidator>
</td>

I needed to add a ValidationGroup to the RequiredFieldValidator, eg,

<asp:RequiredFieldValidator ID="DropDownListRequiredFieldValidator" runat="server"
                            ControlToValidate="ServiceChannelDropDownList"
                            InitialValue="0"
                            ErrorMessage="Channel is required."
                            ValidationGroup="WorkflowValidation" 
                            CssClass="ValidationCss" 
                            EnableTheming="false">*
                        </asp:RequiredFieldValidator>

Thanks all for the help!

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