test.aspx
<form id="form1" runat="server">
<div style="background-color:#9b7cba;">
<asp:DropDownList ID="Sheng" runat="server" AutoPostBack="True" OnSelectedIndexChanged="Sheng_SelectedIndexChanged"></asp:DropDownList>
省
<asp:DropDownList ID="Shi" runat="server" AutoPostBack="True" OnSelectedIndexChanged="Shi_SelectedIndexChanged">
</asp:DropDownList>市
<asp:DropDownList ID="Qu" runat="server">
</asp:DropDownList>区
</div>
</form>
test.aspx.cs
public static SqlConnection myconn;
public static void Open()
{
string connectionString = "server=*;database=*;uid=*;pwd=*";
myconn = new SqlConnection(connectionString);
myconn.Open();
//SqlConnection myconn = new SqlConnection("server=localhost;database=matrixkey;uid=sa;pwd=sa");
}
public static void Close()
{
myconn.Close();
}
public void mat()
{
Open();
string sql_sheng = "select name from province";
SqlCommand cmd = new SqlCommand(sql_sheng, myconn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Sheng.Items.Add(dr["name"].ToString());
}
dr.Close();
Close();
}
/// <summary>
/// 省选定,加载市
/// </summary>
public void rix()
{
string sql_shi = "select city.code,city.name from city,province where province.code = city.provinceID and province.name = '" + Sheng.SelectedItem.Text + "'";
SqlCommand cmd = new SqlCommand(sql_shi, myconn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Shi.Items.Add(dr["name"].ToString());
}
dr.Close();
}
/// <summary>
/// 市选定,加载区
/// </summary>
public void key()
{
string sql_qu = "select area.name from area,city where city.code = area.cityid and city.name = '" + Shi.SelectedItem.Text + "'";
SqlCommand cmd = new SqlCommand(sql_qu, myconn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Qu.Items.Add(dr["name"].ToString());
}
dr.Close();
}
/*在页面加载时,从数据库载入省列表到“省”下拉控件*/
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
mat();
}
}
/*在选定“省”之后,即“省”被改变后*/
/*从数据库载入市列表到“市”下拉控件*/
protected void Sheng_SelectedIndexChanged(object sender, EventArgs e)
{
Shi.Items.Clear(); //标记
Open();
rix();
Close();
}
/*在选定“市”之后,即“市”被改变后*/
/*从数据库载入区列表到“区”下拉控件*/
protected void Shi_SelectedIndexChanged(object sender, EventArgs e)
{
Qu.Items.Clear(); //标记
Open();
key();
Close();
}