Search code examples
c#asp.netdata-bindingdrop-down-menuselectedvalue

Bind SelectedValue of ASP.net DropDownList to custom object


Currently I have a DropDownList inside a FormView, databound to an ObjectDataSource. This is the DropDownList, which has it's own datasource, which returns a List of Departments:

<asp:DropDownList ID="DepartmentsList" DataSourceID="DepartmentsListDataSource" DataTextField="Name" SelectedValue='<%# Bind("Department") %>' runat="server" />

In the datasource of the FormView, the property Department is defined as:

public Department Department { get; set; }

With this situation I get this exception:

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

Logically I get this exception because I haven't set DataValueField on the DropDownList. Question is, what has to be the value of DataValueField if I'd like to databind the complete selected object (of Department) back to the FormViews datasource?

Thanks.


Solution

  • I don't know if it's possible to bind the entire object as the SelectedValue.
    What you could do is bind an unique identifier (e.g. ID) to the DataValueField and retreive your object by it's ID.
    An other (very dirty) solution is to put all the relevant properties (seperated by eg " ; " ) in the DataValueField, and construct your object with these values... But, as said, that's really dirty! ;-)