views:

272

answers:

3

I'm selecting a ListItem as I add it to a ListItemCollection. Then I use that ListItemCollection as a datasource for a DropDownlist but the Selected List Item is not being selected after databind. Here is an example of the code:

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

I'm trying to get this to work so I can return only a list of items, instead of a list of items and the selected value. Is there a way to make the DropDownList select the selected ListItem from the ListItemCollection (or any other type of collection)?

+1  A: 

Hmm... this seems like a strange method to take for accomplishing this, you should be able to do something along these lines:

ddl1.Items.Clear();
foreach(ListItem item in items)
{
   ddl1.Items.Add(item);
}

Which should solve your selection issue...

LorenVS
Hmm, that might be a good work around. Why do you think this is a strange method to be using here? What would you recommend?
mga911
I have just not run across anyone who binds a DropDownList to an ListItemCollection. Usually DropDownList would be bound do some other object that implemented IEnumberable
LorenVS
A: 

I don't think you can set the selected value before you bind to the drop down. I think you have to do it after it has been bound.

klabranche
A: 

Just set the SelectedValue property of your DropDownList :

ddl1.SelectedValue = "Option 2";

Here I'm using a literal string, but it's best to the item.Text value to set it. You can use it before or after the DataBind(), it works either way.

Michael Pereira