views:

20

answers:

1

Hi, I have some HtmlSelect (a'la asp.net's DropDownList) with ID's like Select1, Select2, ..., Select13. I create the static List of items:

for (int i = 0; i < tab.Length; i++)
  _listItems[i] = (new ListItem { Text = tab[0, i], Value = tab[1, i], Selected=false });

then I assign that list for each HtmlSelect control & assign a new SelectedIndex property:

var HtmlSelectControl = ((HtmlSelect)this.FindControl(String.Format("Select{0}", controlNumber)));

HtmlSelectControl.Items.AddRange(_listItems);
HtmlSelectControl.SelectedIndex = controlNumber - 1;

The problem is, when I set the SelectedIndex property of the Select2 control (e.g. =1), the Select1 control has the same SelectedIndex property (which has that index =0). Why ?

A: 

You are binding all of the select controls to the same list of items. It is the items that you are seting as selected when you set the SelectedIndex on the select control. Since all of the select controls have references to the same list of items, setting the SelectedIndex property on one of them sets it on all of the others.

Compare the following two snippets. The first one is the same as yours where you are binding to the same list:

        var _listItems = new List<ListItem>{ new ListItem("Item1"), new ListItem("Item2"), new ListItem("Item3")};
        for (int controlNumber = 1; controlNumber < 4; controlNumber++) {
            var HtmlSelectControl = ((HtmlSelect) this.FindControl(String.Format("Select{0}", controlNumber)));
            HtmlSelectControl.Items.AddRange(_listItems.ToArray());
            HtmlSelectControl.SelectedIndex = controlNumber - 1;
        }

The second one is where you create a seperate list for each dropdown. This is what you need to do:

        for (int controlNumber = 1; controlNumber < 4; controlNumber++) {
            var _listItems = new List<ListItem>{ new ListItem("Item1"), new ListItem("Item2"), new ListItem("Item3")};
            var HtmlSelectControl = ((HtmlSelect) this.FindControl(String.Format("Select{0}", controlNumber)));
            HtmlSelectControl.Items.AddRange(_listItems.ToArray());
            HtmlSelectControl.SelectedIndex = controlNumber - 1;
        }
Daniel Dyson