user2433766
user2433766

Reputation: 33

Selected index of one dropdownlist setting all dropdownlists on the page

I have a webpage with 4 dropdownlists on the page. In the page load method I have the code behind set the values of the dropdownlists. The problem is that when I set any one of the dropdownlists it sets all of the dropdownlists.

    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            //populating the dropdownlist with values
            for (int i = 0; i < 60; i++)
            {
                ListItem temp = new ListItem(i + "");
                ddl_EndMin.Items.Add(temp);
                ddl_StartMin.Items.Add(temp);
                if (i < 24)
                {
                    ddl_EndHour.Items.Add(temp);
                    ddl_StartHour.Items.Add(temp);
                }
            }

            //Setting the dropdownlists with the values from the conference variable
            ddl_EndHour.SelectedIndex = conference.EndDate.Hour;
            ddl_StartMin.SelectedIndex = conference.StartDate.Minute;
            ddl_StartHour.SelectedIndex = conference.StartDate.Hour;
            ddl_EndMin.SelectedIndex = conference.EndDate.Minute;
        }
    }
}

I'm not sure why setting one of these dropdownlists selected index sets all of them. I also tried replacing one of them with a ListBox and the value of the ListBox was set as well. There is code on another page that sets 2 dropdownlists using this selected index method but using states instead of numbers and that works just fine.

ddl_EndMin.SelectedIndex = ddl_EndMin.Items.IndexOf(ddl_EndMin.Items.FindByValue(conference.EndDate.Minute.ToString()));
ddl_EndHour.SelectedIndex = ddl_EndHour.Items.IndexOf(ddl_EndHour.Items.FindByValue(conference.EndDate.Hour.ToString()));

I tried copy/pasting that code into what I'm currently working on and changing the names and I got the same results. Any insight you can give me as to why this problem is occuring would be greatly appreciated.

Upvotes: 3

Views: 1168

Answers (1)

Klors
Klors

Reputation: 2674

At a guess it's because you're using the same item collection in all of your dropdowns.

Then when you set the selected property on one of the items it has that property in all of your lists as it's the same object reference in all lists.

What happens if you do this within the loop

            ListItem temp = new ListItem(i + "");
            ddl_EndMin.Items.Add(temp);
            temp = new ListItem(i + "");
            ddl_StartMin.Items.Add(temp);
            if (i < 24)
            {
                temp = new ListItem(i + "");
                ddl_EndHour.Items.Add(temp);
                temp = new ListItem(i + "");
                ddl_StartHour.Items.Add(temp);
            }

Upvotes: 3

Related Questions