CodersBarn.com
The ASP.NET Community Blog

DropDownList, DataBinding and RequiredValidator

October 17, 2009 09:40 by agrace

I recently had a DropDownList being pre-populated from a database. I also wanted to insert "Select" at the top of the list and make it a required field. Googling this yielded much misinformation for what turned out to be pretty simple to solve in the end.

Say you have a DDL like this:

<asp:DropDownList id="testDDL" runat="server">
    <asp:ListItem Text="Select"></asp:ListItem>
</asp:DropDownList>

 

If we try to populate this DropDownList from a database with the values 1,2 and 3, and then try and add a RequiredFieldValidator, that validator will not fire.

Some people resort to creating a CustomValidator and/or JavaScript here. This is not necessary. We need to take a step back here and re-phrase the problem: We already have data in our list in the shape of the "Select" item. We now want to append data from the database. A quick search of the MSDN documentation leads to the AppendDataBoundItems property for the DropDownList.

From the documentation: "The AppendDataBoundItems property allows you to add items to the ListControl object before data binding occurs. After data binding, the items collection contains both the items from the data source and the previously added items." The italics are mine...

We can use the InitialValue of the RequiredFieldValidator in conjunction with the AppendDataBoundItems property of the DropDownList to arrive at a working solution:

<asp:DropDownList id="testDDL" AppendDataBoundItems="true" runat="server">
    <asp:ListItem Text="Select"></asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="salaryReqVal" ControlToValidate="salaryDDL"
    ErrorMessage="*" Display="dynamic" InitialValue="Select"
        runat="server"></asp:RequiredFieldValidator>

 

kick it on DotNetKicks.com


Tags:
Categories: ASP.NET
Actions: E-mail | Permalink | Comments (4) | Comment RSSRSS comment feed

Comments

October 20. 2009 21:28

trackback

Trackback from DotNetKicks.com

DropDownList, DataBinding and RequiredValidator

DotNetKicks.com

October 20. 2009 21:51

trackback

Trackback from WebDevVote.com

DropDownList, DataBinding and RequiredValidator

WebDevVote.com

October 21. 2009 22:27

trackback

Trackback from DotNetBurner - Javascript

DropDownList, DataBinding and RequiredValidator

DotNetBurner - Javascript

December 11. 2009 08:47

Mike Searles

Thank you for the concise well-written entry.  You were definitely right about all the sites that had information about this problem - confusing and convuluted.  Your information fixed me up in literally 1 minute!  Definitely will be using your site on a regular basis.

Mike Searles

Add comment




  Country flag

biuquote
  • Comment
  • Preview
Loading