using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class citySelect : System.Web.UI.UserControl
{
public event CitySelectHandler OnCitySelect;
/// <summary>
/// 获取用户选择的
/// </summary>
public string ProvinceCity
{
get
{
return this.DropDownList1.SelectedItem.Text +
"(" +
this.DropDownList1.SelectedValue +
");" +
this.DropDownList2.SelectedItem.Text +
"(" +
this.DropDownList2.SelectedValue +
")";
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
bindProvince();
}
private void bindProvince(){
string str = System.Configuration.ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
using(SqlConnection sqlcnn = new SqlConnection(str)){
using(SqlCommand sqlcmm = sqlcnn.CreateCommand()){
sqlcmm.CommandText = "select provinceid,province from province";
sqlcnn.Open();
DropDownList1.DataSource = sqlcmm.ExecuteReader();
DropDownList1.DataTextField = "province";
DropDownList1.DataValueField = "provinceid";
DropDownList1.DataBind();
}
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e){
this.DropDownList2.Items.Clear();
string pid = this.DropDownList1.SelectedValue;
string str = System.Configuration.ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
using (SqlConnection sqlcnn = new SqlConnection(str)){
using (SqlCommand sqlcmm = sqlcnn.CreateCommand()){
sqlcmm.CommandText = "select cityid,city from city where father='" + pid + "'";
sqlcnn.Open();
DropDownList2.DataSource = sqlcmm.ExecuteReader();
DropDownList2.DataTextField = "city";
DropDownList2.DataValueField = "cityid";
DropDownList2.DataBind();
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
//Label lbl = this.Parent.FindControl("Label1") as Label;
//lbl.Text = this.DropDownList2.SelectedItem.Text;
if (OnCitySelect != null)
{
OnCitySelect(this, this.DropDownList2.SelectedItem.Text);
}
}
}
public delegate void CitySelectHandler(object sender,string selectCity);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.city1.OnCitySelect +=
new CitySelectHandler(city1_OnCitySelect);
}
void city1_OnCitySelect(object sender, string selectCity)
{
this.Label1.Text = selectCity;
}
protected void Button1_Click(object sender, EventArgs e)
{
#region 方法一
DropDownList ddl = this.city1.FindControl("DropDownList1") as DropDownList;
if (ddl != null)
this.Label1.Text = "省份:" + ddl.SelectedItem.Text + "(" + ddl.SelectedValue + ");";
ddl = this.city1.FindControl("DropDownList2") as DropDownList;
if (ddl != null)
this.Label1.Text += "城市:" + ddl.SelectedItem.Text + "(" + ddl.SelectedValue + ");";
#endregion
this.Label1.Text = this.city1.ProvinceCity;
}
}