Reputation: 17
I'm trying to set the selected index or value of two DropDownList
that are populated from an array.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ListItem[] jobs;
List<ListItem> data = new List<ListItem> {
new ListItem("Hello", "World"),
new ListItem("new", "item"),
new ListItem("next", "item2"),
new ListItem("four", "four")
};
jobs = (from x in data
select new ListItem(x.Text, x.Value)).ToArray();
// jobs is any array of list items where
// text = value or text != value, but value is unique.
DropDownList1.Items.AddRange(jobs);
DropDownList2.Items.AddRange(jobs);
DropDownList1.SelectedIndex = 1;
DropDownList2.SelectedValue = jobs[3].Value;
}
}
On the actual page both DropDownList
have "four" selected. How can I set different values?
Note: I know using linq is not needed here, but in the project code data is from a SQL DB.
Upvotes: 0
Views: 413
Reputation: 176
Items.AddRange(array)
preforms a shallow copy of array.
to preform a deep copy change
DropDownList1.Items.AddRange(jobs);
to
DropDownList1.DataSource = jobs;
DropdownList1.DataBind();
repeat for the other list.
Upvotes: 0
Reputation: 3265
Create another ListItem jobsClone
ListItem[] jobsClone = new ListItem[jobs.Length];
for (int i = 0; i < jobs.Length; i++)
{
jobsClone[i] = new ListItem(jobs[i].Value);
}
then You can set your SelectedIndex
DropDownList1.Items.AddRange(jobs);
DropDownList2.Items.AddRange(jobsClone);
DropDownList1.SelectedIndex = 1;
DropDownList2.SelectedIndex = 3;
Upvotes: 1