DataBinding ListItemCollection to DropDownList

G

Guest

Hi,

I have a ListItemCollection that I bind to DropDownList:
ListItemCollection items = new ListItemCollection();
ListItem item;
item = new ListItem("Option 1", "1");
items.Add(item);
item = new ListItem("Option 2", "2");
item.Selected = true;
items.Add(item);
ddl1.DataSource = items;
ddl1.DataBind();

As you see the second ListItem is selected and should be selected in the
dropdownlist. But isn't!

However, if i use:
<asp:DropDownList runat="server" ID="test2">
<asp:ListItem Text="1" />
<asp:ListItem Selected="True" Text="2" />
</asp:DropDownList>

Everything works as expected.

Is there an explanation to this? And is there a possible solution? I guess
one could put the selected ListItem fist in the DropDownList but this would
mess up the option and isn't a good solution for me.

Thanks in advance

Richard
 
G

Guest

ListControl.DataSource property will only pickup the DataTextFiled and
DataValueField from your collection.
http://msdn.microsoft.com/library/d...ndowsformslistcontrolclassdatasourcetopic.asp

For that purpose you can use any collection that implements the ILIST
interface (i.e. you did not have to use a ListItemCollection). If you are
interested in composing the list items like you did, you should have used a
simple array of type ListItem like this:

ListItem[] items = new ListItem[2];
items[0] = new ListItem("Option 1", "1");
items[1] = new ListItem("Option 2", "2");
items[1].Selected = true;
ddl1.AddRange (items);
 

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,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top