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

Brock Allen

SelectedItem is the Item in the list. It has Text and Value properties. That's
what you want to access.
 
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.
 
Joined
Jan 3, 2011
Messages
1
Reaction score
0
ASP Net - DropDownList Bound to ArrayList of Custom Objects

Wonderful! So you found an alternative way of doing it. Great for you! Unfortunately, it leaves the rest of us still wondering how to do it through the DropDownList.
 

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

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,077
Latest member
SangMoor21

Latest Threads

Top