ASP.NET AJAX DropDownList
html Code
@asp:dropdownlist id="ddlCountry" runat="server" onselectedindexchanged="ddlCountry_SelectedIndexChanged" autopostback="True"@@/asp:dropdownlist@
@asp:updatepanel id="upnl" runat="server"@
@contenttemplate@
@asp:dropdownlist id="ddlState" runat="server"@@/asp:dropdownlist@
@/contenttemplate@
@triggers@
@asp:asyncpostbacktrigger controlid="ddlCountry"@
@/asp:asyncpostbacktrigger@
@/triggers@
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection con = new SqlConnection("Data Source=SERVER; Integrated Security=SSPI;persist security info=True;Initial Catalog=DBNAME;");
SqlCommand cmd = new SqlCommand("SELECT CountryName,CountryId FROM CountryTable", con);
DataTable dt = new DataTable();
con.Open();
SqlDataAdapter adptr = new SqlDataAdapter(cmd);
adptr.Fill(dt);
con.Close();
if (dt.Rows.Count > 0)
{
ddlCountry.Items.Clear();
ddlCountry.Items.Add("SELECT");
foreach (DataRow drow in dt.Rows)
{
ListItem lst = new ListItem();
lst.Value = drow[1].ToString();
lst.Text = drow[0].ToString();
ddlCountry.Items.Add(lst);
}
}
}
}
protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlCountry.SelectedValue.ToString() != "SELECT")
{
SqlConnection con = new SqlConnection("Data Source=SERVER; Integrated Security=SSPI;persist security info=True;Initial Catalog=DBNAME;");
SqlCommand cmd = new SqlCommand(string.Format("SELECT StateName,StateId FROM StateTable WHERE CountryId='{0}'", ddlCountry.SelectedValue.ToString()), con);
DataTable dt = new DataTable();
con.Open();
SqlDataAdapter adptr = new SqlDataAdapter(cmd);
adptr.Fill(dt);
con.Close();
if (dt.Rows.Count > 0)
{
ddlState.Items.Clear();
ddlState.Items.Add("SELECT");
foreach (DataRow drow in dt.Rows)
{
ListItem lst = new ListItem();
lst.Value = drow[1].ToString();
lst.Text = drow[0].ToString();
ddlState.Items.Add(lst);
}
}
}
}
No comments:
Post a Comment