DropDownList Bound to ArrayList of Custom Objects

  • Thread starter Thread starter phlian
  • Start date Start date
P

phlian

I've got a dropdownlist (webform) bound to an arraylist which holds my
several of a custom object as follows:

fldOption.DataSource = prod.Items
fldOption.DataTextField = "Options"
fldOption.DataValueField = "ID"
fldOption.DataBind()

(prod.Items is an arraylist containing objects of type cItem)

Seems straight forward enough, and the control works fine.

The problem comes when I try to get a reference to the cItem that is
selected. One would think that:

dim i as cItem = CType(fldOption.SelectedItem, cItem)

would do the trick...but it doesn't. Instead I get:

Value of type 'System.Web.UI.WebControls.ListItem' cannot be converted
to 'cItem'.

Yes, I could simply loop through the prod.Items arraylist and look for
matching IDs...in fact I'll probably go code it that way now, since I
need to get this done. But that seems to be a less than elegant
solution to the problem.

Am I misunderstanding something here? Any help appreciated.
 
Thank you for your reply.

I understand the Text and Value properties, but I need access to all
the properties and methods on the cItem object, so they don't help me
here.

Alternately, I'm wondering if the items in the dropdownlist are always
in the same order as the items in the arraylist. If that's the case, I
could simply refer to prod.items(fldOption.SelectedIndex), which would
certainly be cleaner than doing a for...each through the arraylist,
which can be fairly large.
 
Alternately, I'm wondering if the items in the dropdownlist are always
in the same order as the items in the arraylist. If that's the case,
I could simply refer to prod.items(fldOption.SelectedIndex), which
would certainly be cleaner than doing a for...each through the
arraylist, which can be fairly large.

Yes that would probabaly work. I'd tend to be more defensive and find the
cItem entry in the collection based upon the ID. You'd want to use Array.BinarySearch
to do that.

-Brock
DevelopMentor
http://staff.develop.com/ballen
 
Back
Top