I have kept this article developer friendly which means you don’t need to write much Javascript and will be writing .NET code only, which you love.
So today we’ll be creating dependent dropdownlist which pulls out Cities for a State. We’ll have 2 dropdownlists
1. ddlState - which shows Indian States
2. ddlCity - which contains cities in those states
To start with create a project in VS.NET using ASP.NET AJAX template because it enters information regarding AJAX extensions into your web.config. Put these code elements into your aspx
<form id=”form1″ runat=”server”>
<div>
<asp:ScriptManager ID=”ScriptManager1″ runat=”server”>
</asp:ScriptManager>
<asp:UpdatePanel ID=”up1″ runat=”server”>
<ContentTemplate>
<table border=”0″>
<tr>
<td>
State :
</td>
<td>
<asp:DropDownList ID=”ddlState” runat=”server”
OnSelectedIndexChanged=”ddlState_SelectedIndexChanged”
AutoPostBack=”true”>
<asp:ListItem Text=”Andhra” Selected=”True”></asp:ListItem>
<asp:ListItem Text=”Punjab”></asp:ListItem>
<asp:ListItem Text=”Karnataka”></asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td>
Cities :
</td>
<td>
<asp:DropDownList ID=”ddlCity” runat=”server”>
</asp:DropDownList>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
And this is how your code behind should look like
protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
{
ddlCity.Items.Clear();
if (ddlState.SelectedValue == “Punjab”)
{
ddlCity.Items.Add(new ListItem(“Ludhiana”));
ddlCity.Items.Add(new ListItem(“Mohali”));
ddlCity.Items.Add(new ListItem(“Amritsar”));
}
else if (ddlState.SelectedValue == “Andhra”)
{
ddlCity.Items.Add(new ListItem(“Hyderabad”));
ddlCity.Items.Add(new ListItem(“Vijaywada”));
ddlCity.Items.Add(new ListItem(“Warangal”));
}
else if (ddlState.SelectedValue == “Karnataka”)
{
ddlCity.Items.Add(new ListItem(“Bangalore”));
ddlCity.Items.Add(new ListItem(“Mangalore”));
ddlCity.Items.Add(new ListItem(“Mysore”));
}
}
You can run and test the application by selecting different values from the State combo box and noting that City list is populated by the server without refreshing the entire page. This is how your page should look like in the output
1 comment:
This stuff don't work at all.. use trigger with control id and event parameter enough ady..
Post a Comment