Problem with getting selected OBJECT from dropdown

2019-05-11 13:39发布

问题:

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:

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)



回答2:

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).



回答3:

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.



回答4:

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<User> (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<User> 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];