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);
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();
AddRange wants an array of ListItems. you can do it like this (C# 3+).
drpTypesCreateEdit.Items.AddRange(drpTypes.Items.OfType<ListItem>().ToArray());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With