Bind SelectedValue ASP.net DropDownList for custom object

I currently have a DropDownList inside a FormView, binding data to an ObjectDataSource. This is a DropDownList that has its own data source that returns a list of departments:

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

In a FormView data source, a property department is defined as:

 public Department Department { get; set; } 

In this situation, I get this exception:

'DepartmentsList' has a SelectedValue value, which is not valid because it does not exist in the list of elements. Parameter Name: Value

Logically, I get this exception because I did not set the DataValueField to DropDownList. The question is what should be the value of a DataValueField if I would like to bind the full selected object (department) to the FormViews data source?

Thanks.

+2
c # drop-down-menu data-binding
source share
2 answers

I do not know if it is possible to link the whole object as a SelectedValue .

What you can do is bind a unique identifier (e.g. ID) to a DataValueField and return your object by its identifier.
Another ( very dirty ) solution is to put all the relevant properties (separated, for example, ";") in the DataValueField , and build your object with these values ​​... But, as said, this is really dirty !; -)

+1
source share

You can assign a DataValueField object, but it will not work, since your object will be passed to a string. This means that you will have the same string value for all your bound options, the value may be the type of your object or just an object. The approach may be the one that was formulated by Peter Nijs, sharing in character the corresponding properties of the object, but, as he said, it is very dirty.

0
source share

All Articles