Note that there are some explanatory texts on larger screens.

plurals
  1. POProblems issuing DropDownList.Items.Addrange and selecting a value
    text
    copied!<p>I'm new to C#, as I mainly have been using Java.</p> <p>But straight to the problem (which I have simplified a bit):</p> <p>First an excerpt of my aspx-page:</p> <pre><code>&lt;div class="dates"&gt; &lt;div class="firstselection"&gt; &lt;asp:DropDownList ID="DDFromMonth" runat="server"&gt; &lt;/asp:DropDownList&gt; &lt;asp:DropDownList ID="DDToMonth" runat="server"&gt; &lt;/asp:DropDownList&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>And the codebehind:</p> <pre><code> public partial class Argh: System.Web.UI.Page { static List&lt;ListItem&gt; monthList = new List&lt;ListItem&gt; { new ListItem("Jan", "1"), new ListItem("Feb", "2"), new ListItem("Mar", "3"), new ListItem("Apr", "4"), new ListItem("May", "5"), new ListItem("Jun", "6"), new ListItem("Jul", "7"), new ListItem("Aug", "8"), new ListItem("Sep", "9"), new ListItem("Oct", "10"), new ListItem("Nov", "11"), new ListItem("Dec", "12") }; protected void Page_Load(object sender, EventArgs e) { DDFromMonth.Items.AddRange(monthList.ToArray()); // DDFromMonth is a asp.net dropdown list DDToMonth.Items.AddRange(monthList.ToArray()); // DDToMonth is a asp.net dropdown list DDFromMonth.SelectedValue = "6"; DDToMonth.SelectedValue = "7"; // also changes DDFromMonth value (GODDAMN!) } </code></pre> <p>Ok, I have a static list that contains the months. I add the range of this list to both dropdown-controls and DDFromMonth I select "6" (June) and DDToMonth "7" (July). However, this results in both dropdownlists show July!</p> <p>I also tried with a non-static list, but that doesn't matter. The only thing I tested that "works" is to instantiate two different lists - only then the dropdownlist-items are selected as I wish. So, adding the lists like this make things work (but is ugly):</p> <pre><code>DDFromMonth.Items.AddRange(monthList.ToArray()); DDFromMonth.Items.AddRange(aDuplicatedMonthList.ToArray()); </code></pre> <p>I have worked around this by adding datasources via asp.net, but still, it would be interesting to know what is happening here. Why do I have to instantiate a new list for each dropdown list. Doesn't each control have own pointers that keep track of their own values? It feels like the pointers are shared in the list somehow, but I leave ponderings to someone that better knows C# and ASP.NET</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload