How to get the selected value in a DropDownList in the Object Type (not string)?
I fill up a List<> with an object that has properties. I can bind to the DropDownList without any problem:
cbo.DataSource = possibleChoice;
cbo.DataValueField = "Value";
cbo.DataTextField = "Display";
cb开发者_StackOverflow社区o.DataBind();
But I can't find a way to get the Value. I know the DropDownList has SelectedValue but it return a String instead of my type of object...
MyObjectType myObj = (MyObjectType)this.cbo.SelectedValue;//Err! Return a String
How can I get the object from the DropDownList?
I think you should be able to do the following
MyObjectType myObj = (MyObjectType)this.cboTimeArea.SelectedItem.Value;
But if not, the following will work
MyObjectType myObj = possibleChoice[this.cboTimeArea.SelectedIndex];
I typically store a string representation of the ID as the SelectedValue
, then grab the object from a data store (Cache, Session data, database, ViewState, etc.--whatever is appropriate) on postback, i.e. after you reconstitute your possiblechoices
.
The DropDownList
doesn't store the objects you databind to it.
It's best to specify DataValueField as the ID of the object, then you can do something like this:
cbo.DataSource = possibleChoice;
cbo.DataValueField = "Id";
cbo.DataTextField = "Display";
cbo.DataBind();
var userChoice = possibleChoice
.Where(x => x.Id == Convert.ToInt(cbo.SelectedValue));
精彩评论