Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting SelectedValue for one DropDownList also updates the SelectedValue for another DropDownLIst

Tags:

asp.net

I have a WebForms page that has two DropDownList controls on it that both contain a range of temperatures from 60-80 degrees, one for heating the other for cooling. They are declared in the .aspx as:

<asp:DropDownList ID="heating" runat="server" />
<asp:DropDownList ID="cooling" runat="server" />

The values for each list are populated in the code-behind using:

for(int i = 60; i <= 80; i++)
{
    var listItem = new ListItem(i + " degrees", i.ToString());

    heating.Items.Add(listItem);
    cooling.Items.Add(listItem);
}

When I try to set the selected value for each DropDownList using the values in an object containing data loaded from the database using:

heating.SelectedValue = myHome.avgHeatingTemp.ToString();
cooling.SelectedValue = myHome.avgCoolingTemp.ToString();

The SelectedValue for both lists is set first to the value in myHome.avgHeatingTemp, then to the value in myHome.avgCoolingTemp. I have no idea why this is happening or how to fix it.

Heres what the values are for each variable after each step of the process of setting the SelectedValues:

Initial State
    heating.SelectedValue: 60
    cooling.SelectedValue: 60
    myHome.avgHeatingTemp: 72
    myHome.avgCoolingTemp: 75

After setting heating.SelectedValue
    heating.SelectedValue: 72
    cooling.SelectedValue: 72
    myHome.avgHeatingTemp: 72
    myHome.avgCoolingTemp: 75

After setting cooling.SelectedValue
    heating.SelectedValue: 75
    cooling.SelectedValue: 75
    myHome.avgHeatingTemp: 72
    myHome.avgCoolingTemp: 75
like image 565
Hamman359 Avatar asked Jul 21 '10 17:07

Hamman359


1 Answers

You are binding those to the same instance of the ListItem object. So, when you select one, it's also selecting the other. When you populate the dropdownlists, try creating two instances of ListItem.

for(int i = 60; i <= 80; i++)
{
    var listItem1 = new ListItem(i + " degrees", i.ToString());
    var listItem2 = new ListItem(i + " degrees", i.ToString());

    heating.Items.Add(listItem1);
    cooling.Items.Add(listItem2);
}

This happens because the ListItem itself has a Selected property. When you set it for one, you set it for the other as well.

like image 157
EndangeredMassa Avatar answered Oct 12 '22 02:10

EndangeredMassa