Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here's what you do. </p> <p>In the ASPX code:</p> <pre><code>&lt;asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddl_SelectedIndexChanged"&gt; &lt;asp:ListItem Text="1" Value="1" /&gt; &lt;asp:ListItem Text="2" Value="2" /&gt; &lt;asp:ListItem Text="3" Value="3" /&gt; &lt;asp:ListItem Text="4" Value="4" /&gt; &lt;/asp:DropDownList&gt; &lt;asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddl_SelectedIndexChanged"&gt; &lt;asp:ListItem Text="1" Value="1" /&gt; &lt;asp:ListItem Text="2" Value="2" /&gt; &lt;asp:ListItem Text="3" Value="3" /&gt; &lt;asp:ListItem Text="4" Value="4" /&gt; &lt;/asp:DropDownList&gt; &lt;asp:DropDownList ID="DropDownList3" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddl_SelectedIndexChanged"&gt; &lt;asp:ListItem Text="1" Value="1" /&gt; &lt;asp:ListItem Text="2" Value="2" /&gt; &lt;asp:ListItem Text="3" Value="3" /&gt; &lt;asp:ListItem Text="4" Value="4" /&gt; &lt;/asp:DropDownList&gt; </code></pre> <p>In the codebehind:</p> <pre><code>protected void ddl_SelectedIndexChanged(object sender, EventArgs e) { DropDownList ddl = (DropDownList)sender; string value = ddl.SelectedValue; SetValue(DropDownList1, value); SetValue(DropDownList2, value); SetValue(DropDownList3, value); } protected void SetValue(DropDownList ddl, string value) { ddl.SelectedIndex = ddl.Items.IndexOf(ddl.Items.FindByValue(value)); } </code></pre> <p>Just typing <code>ddl1.SelectedValue = ddl2.SelectedValue</code> won't work, because <code>DropDownList.SelectedValue</code> is read-only. </p> <p>Note that I didn't just set the <code>SelectedIndex</code> of all the DDLs to that of the sender. You <strong>can</strong> use that in your example scenario, but if one of your DDLs ever has its ListItems in a different order from the others, the code will break. In my opinion, this makes it dangerous practice, but YMMV. </p> <p>Also, if you decide to generalize the SetValue method (I often add it as an extension method to the <code>DropDownList</code> control across the entire project), you should handle cases where the target value isn't found in the DDL, presumably by throwing an exception. You can also make a SetText version using <code>FindByText</code>.</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