Friday, 22 December 2006

DropDownList SelectedValue exception

'DropDownList1' has a SelectedValue which is invalid because it does not exist in the list of items. Parameter name: value

I have found many people have this exception in their dropdownlist databinding. It's annoying when upgrade an application from asp.net 1.1 to 2.0. Code used to work now breaks.

This exception is caused when a drop down list has been bound to a datasource, with a item selected, the .net runtime tries to bind the drop down list to a new datasource with different data, and the selected value is not in the new datasource.

There is one work around which needs to set the AppendDataBoundItems property to true. This works if the drop down list is bound only once. If it's bound several times, the item list will grow with repeatitive values.

The only workable solution I have found is to do this:

In the stored procedure, put a union select top item for the list as
select Text, Value from Customer
union
select '', null

In the client side, whenever before the list is bound, put a line of code like this:

Dropdownlist1.SelectedValue = ''


This would solve the problem.

Sunday, 3 December 2006

In custom control the ID property of child controls must be unique

When we create a composite web custom control, often we create child controls in the override CreateChildControls() method. At this time we assign a text value to ID property of each child control. There is a little bit tricky of this ID property. The ID value should be unique across the whole page, not only in the control itself. Say if we have a TextBox with ID "txtValue", when we put two controls in a page and call FindControl("txtValue"), the runtime throws an exception says there are multiple controls have the same txtValue ID value. This is because asp.net assign the same txtValue to two text box in a same page.

To solve this problem, we alway prefix the control's client id with the child id to ensure uniqueness. For example, we can set this.ClientID + "txtValue" to the TextBox ID property. Because the ClientID of a custom control is unique, the ID of each child control is always unique too.