views:

117

answers:

3

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";
     cbo.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?

+2  A: 

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];
JaredPar
+1  A: 

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.

Dave
+1  A: 

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));
Kirschstein