Friday, November 23, 2007

ASP.NET 2.0 and up : RequiredField Validator and DropDownList

Simple: to validate a dropdownlist, the following is required:

1. AppendDataBoundItems="true" (this property allows us to add static items to the databound collection)

2. Have an item that has a value of 0 :

<asp:ListItem Text="Please select an item" Value="0" Selected="true" />



3. Add a required field validator with the property "InitialValue" set to 0.




<asp:RequiredFieldValidator runat="server" id="RequiredDropDown" 
ControlToValidate="DropDownList1" InitialValue="0" ErrorMessage="Please select an Item" />



Here's the complete Code Listing





   1: <asp:DropDownList ID="ddlPhases" runat="server" DataSourceID="sqldatasource1" Width="183px"


   2:     DataTextField="Phase" DataValueField="PhaseID" AppendDataBoundItems="true">


   3:     <asp:ListItem Text="Select a phase" Value="0" />


   4: </asp:DropDownList>


   5:  


   6: <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="ddlPhases"


   7:     Display="Dynamic" InitialValue="0" ErrorMessage="Pleas Select a Phase" />


   8:  


   9: <asp:SqlDataSource ID="sourcePhases" runat="server" ConnectionString="<%$ ConnectionStrings:CnString %>"


  10:     SelectCommand="Select PhaseID, Phase From Phase" />



2 comments:

Lev from Israel said...

Thank for this biggest solution.
I did not undertand that i should add first non-dynamic row. Once more : greatest solution

oudinia said...

Thanks !

Glad it could help.

the InitialValue and the dropdownList go together to do validation, as long as you have a default selected item.

happy programming!