// default.aspx //
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title> Dropdowns Sample</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table align="center">
<tr>
<td>
Select Country:
</td>
<td>
<asp:DropDownList ID="ddlCountry" runat="server" AutoPostBack="true"
onselectedindexchanged="ddlCountry_SelectedIndexChanged"></asp:DropDownList>
</td>
</tr>
<tr>
<td>
Select State:
</td>
<td>
<asp:DropDownList ID="State" runat="server" AutoPostBack="true"
onselectedindexchanged="State_SelectedIndexChanged"></asp:DropDownList>
</td>
</tr>
<tr>
<td>
Select Region:
</td>
<td>
<asp:DropDownList ID="Region" runat="server"></asp:DropDownList>
</td>
</tr>
</table>
</div>
</form>
</body>
// default.aspx.cs //
private String strConnection = "Data Source=.;Initial Catalog=rnp;Integrated Security=True";
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
Binddropdown();
}
}
protected void Binddropdown()
{
SqlConnection con = new SqlConnection(strConnection);
con.Open();
SqlCommand cmd = new SqlCommand("select * from CountryTable", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
Country.DataSource = ds;
Country.DataTextField = "CountryName";
Country.DataValueField = "CountryID";
Country.DataBind();
Country.Items.Insert(0, new ListItem("--Select--", "0"));
State.Items.Insert(0, new ListItem("--Select--", "0"));
Region.Items.Insert(0, new ListItem("--Select--", "0"));
}
protected void Country_SelectedIndexChanged(object sender, EventArgs e)
{
int CountryID = Convert.ToInt32(Country.SelectedValue);
SqlConnection con = new SqlConnection(strConnection);
con.Open();
SqlCommand cmd = new SqlCommand("select * from StateTable where CountryID="+CountryID, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
State.DataSource = ds;
State.DataTextField = "StateName";
State.DataValueField = "StateID";
State.DataBind();
State.Items.Insert(0, new ListItem("--Select--", "0"));
if(State.SelectedValue=="0")
{
Region.Items.Clear();
Region.Items.Insert(0, new ListItem("--Select--", "0"));
}
}
protected void State_SelectedIndexChanged(object sender, EventArgs e)
{
int StateID = Convert.ToInt32(State.SelectedValue);
SqlConnection con = new SqlConnection(strConnection);
con.Open();
SqlCommand cmd = new SqlCommand("select * from RegionTable where StateID=" + StateID, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
Region.DataSource = ds;
Region.DataTextField = "RegionName";
Region.DataValueField = "RegionID";
Region.DataBind();
Region.Items.Insert(0, new ListItem("--Select--", "0"));
}
// SQL Table //
1. Country Table
2. State Table
3. Region Table
No comments:
Post a Comment