I am trying to setup a cascaded drop down box where the first one will result in the second one’s value being changes and so on. I have some markup like this:
<form id="ddlSelections" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" />
<asp:UpdatePanel ID="UpdatePanel2" runat="server" ChildrenAsTriggers="true" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="DDL1" EventName="SelectedIndexChanged" />
<asp:AsyncPostBackTrigger ControlID="DDL2" EventName="SelectedIndexChanged" />
</Triggers>
<ContentTemplate>
<asp:DropDownList ID="DDL1" OnSelectedIndexChanged="OnDDL1Change" AutoPostBack="true" runat="server" />
<asp:DropDownList ID="DDL2" OnSelectedIndexChanged="OnDDL2Change" AutoPostBack="true" runat="server" />
<asp:DropDownList ID="DDL3" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
And my code-behind is something like this:
protected void Page_Load(object sender, EventArgs e)
{
populateDDL1();
}
private void populateDDL1()
{
DDL1.Items.Clear();
// -- populate from SQL
}
protected void OnDDL1Change(object sender, EventArgs e)
{
DDL2.Items.Clear();
// -- populate from SQL
}
This is working except that everytime I click on the first drop down box, the values in the second drop down box get populated but the values in the first drop down box are being re-populated i.e. it looks like populateDDL1() is being called which of course will not be called unless Page_Load is called! I am failing to understand why this is the case. Any suggestions on where I am going wrong?
You are populating the first dropdownlist on every page load.
You need to do that only on the first load.
Wrap your
populateDDL1call inif (!IsPostBack), which is a backward way of saying to only populate it the first time the page loads.To test this, put a breakpoint on that line in
Page_Load.Just because it’s an ajax-y
UpdatePaneldoesn’t mean that the server-side methods don’t run.