views:

88

answers:

4

I have a problem with getting selected objectfrom my list.

I bind collection of users to dropdownlist by:

 ddlContractors.DataSource = service.GetAllUsers();
                ddlContractors.DataTextField = "Name";
                ddlContractors.DataValueField = "Id";
                ddlContractors.DataBind();

It's working. But when I try getting selected object by:

var user = (User)ddlContractors.SelectedItem;

I get:

    (User)ddlContractors.SelectedItem   Cannot convert type 'System.Web.UI.WebControls.ListItem' to 'GWDSite.GWDService.User'

How can I get object user from dropdownlist ? I can change type of my list control if it is necessary

+1  A: 

use SelectedValue instead of SelectedItem

WEB APPLICATION

As you are working with web app , approach i was describng will not work here.

you can get the ID of the selected item and use this ID as a parameter to retrive the object from the service layer but if the object is expensive to create than use caching to store your object and retrive it wheb needed.

saurabh
no, it gives the same result
+2  A: 

The value field in the dropdown list is the field "Id" not the User object. so 'SelectedItem' is returning the "Id" value -- not the object. You can use that Id to lookup the User object (from session or cache or wherever you can keep it)

Jim Ecker
+1  A: 

You cant.

The SelectedItem is of type ListItem and you cannot just typecast a listItem back into your custom class i.e user.

You can only get the text or the value associated with the item that was selected via SelectedItem / SelectedValue

What you need to do is use that text / value and maybe retrieve your corresponding "User" object based on that text / value from somewhere (depending on how you are doing your state management).

InSane
in case of WPF /Silverlight, you can get the actual user object by uisng DataContext
saurabh
A: 

Let me show u a little trick (i have no idea if u shud do things this way or not, but it works)...i'm assuming service.GetAllUsers() returns a List (no problem if it returns DataTable or Array, the trick still apply in the respective context). So, when u're selecting a user name from ur ddlContractors u HAVE a SelectedIndex right? Store it -

int index = ddlContractors.SelectedIndex;

Now, since List is serving as the DataSource of ddlContractors u have ur expected User object (whose name was selected) at the same index of List -

User userObject = userList[index];

...hey don't laugh if its kinda funny (i'm a VERY immatured programmer). ...and plz let me know if this approach to solve the problem is acceptable.

:-)

Nero