DropDownList Bound to ArrayList of Custom Objects

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

Phillip Ian

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

Brock Allen

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top