Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy items from one DropDownList to another

How can I copy items hardcoded from one dropdown box to another keeping the keys and values?

drpTypes.Items.Add(new ListItem("Tipos de Acções", "1"));
drpTypes.Items.Add(new ListItem("Tipos de Combustível", "2"));
drpTypes.Items.Add(new ListItem("Tipos de Condutor", "3"));

drpTypesCreateEdit.Items.AddRange(drpTypes.Items);
like image 393
LuRsT Avatar asked Apr 19 '10 13:04

LuRsT


2 Answers

Agree with Anthony's comment above.

However, since the selected ListItems will still refer to the same objects of the original DropDownList, there will be unintended side-effects when changing fields/properties.

For example:

drpTypes.Items.Add(new ListItem("Tipos de Acções", "1"));
drpTypes.Items.Add(new ListItem("Tipos de Combustível", "2"));
drpTypes.Items.Add(new ListItem("Tipos de Condutor", "3"));

drpTypesCreateEdit.Items.AddRange(drpTypes.Items);

drpTypes.SelectedValue = "2";
drpTypesCreateEdit.SelectedValue = "3";

Both drpTypes and drpTypesCreateEdit now have SelectedValue of "3", whereas that is clearly not the intent of the above code.

Instantiating new ListItem objects instead of just selecting the original object will fix this:

drpTypesCreateEdit.Items.AddRange(drpTypes.Items.Cast<ListItem>().Select(x => New ListItem(x.Text, x.SelectedValue)).ToArray();
like image 105
Jordan Parker Avatar answered Oct 07 '22 18:10

Jordan Parker


AddRange wants an array of ListItems. you can do it like this (C# 3+).

drpTypesCreateEdit.Items.AddRange(drpTypes.Items.OfType<ListItem>().ToArray()); 
like image 40
Anthony Pegram Avatar answered Oct 07 '22 18:10

Anthony Pegram