RequiredFieldValidator on drop down list not accepting IntialValue for null object
I have read through this which helped me narrow down my validation problems to the InitialValue
property of the RequiredFieldValidator
.
My drop down list is a list of objects which are populated by the code behind like this;
brands.Insert(0, Brand.Empty)
cbBrand.DataValueField = "ID";
cbBrand.DataTextField = "Name";
cbBrand.DataSource = new BindingList<Brand>(brands);
cbBrand.DataBind();
where Brand.Empty is a null object type.
Where I'm coming unstuck is getting the IntialValue
to accept a null value. For instance, InitialValue=开发者_Go百科""
fails to recognise the empty object in the list.
Can anyone point me in the direction of a fix for this?
An empty string is not the same as a null value. Instead of adding a null value to your data source, add it to the drop down directly like :
cbBrand.Insert(0, new ListItem("", "Select an item"));
That will add a option to your HTML select element with a value of "", which matches the validators initial value.
Wow. I thought I had searched previous answers on this site very thoroughly before posting this question, but I had missed this!!
The answer is to change your <asp:DropDownList>
to have the property AppendDataBoundItems=true
, Then add an <asp:ListItem Text="" Value="" />
between the dropDownList tags and BAM! you can insert a value to the list that does not require the null object inserted in the code behind (which should be removed so that you don't end up with 2 blanks at the start of your list).
The benefit here is that the list in my code-behind is bound to an object type <Brand>
, but adding the empty string at the client works fine for client-side validation.
Hope this helps anyone else struggling with this problem!
精彩评论