您的位置:首页 > 编程语言 > ASP

AJAX+ASP.NET无刷新二级联动省市下拉列表

2008-05-27 11:12 483 查看
TwoDropDownList.aspx 中的代码如下:
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<div>
<asp:UpdatePanel id="UpdatePanel2" runat="server">
<contenttemplate>
<asp:DropDownList id="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DDL1_SelectedIndexChange"></asp:DropDownList>
<asp:DropDownList id="DropDownList2" runat="server"></asp:DropDownList>
</contenttemplate>
</asp:UpdatePanel>
</div>

TwoDropDownList.aspx.cs 中的代码如下:
using System.Data.SqlClient;
public partial class Register2 : System.Web.UI.Page
{
SqlConnection conn = connsql.ZYJCreateConnection();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDrop();
}
}

private void BindDrop()
{
//将数据捆绑到下拉列表中
string sql = "select * from Province";
SqlDataAdapter myCommand = new SqlDataAdapter(sql, conn);
DataSet myds = new DataSet();
myCommand.Fill(myds, "Authors");
DropDownList1.DataSource = myds.Tables["Authors"].DefaultView;
DropDownList1.DataTextField = "Province_Name"; //设置列表显示的字段
DropDownList1.DataValueField = "Province_ID"; //设置列表提交后获得的字段
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("请选择省份名", ""));//第一项中加入内容,重点是绑定后添加

DropDownList2.Items.Insert(0, new ListItem("请选择城市名", ""));//第一项中加入内容,重点是绑定后添加
}

protected void DDL1_SelectedIndexChange(object sender, EventArgs e)
{
//注:在SQL语句中的函数 substring(dqdm,1,2) 是从数字1开始算起;而在C#中 Substring(0, 2) 是从0开始算起;
string sql2 = "select * from City where substring(City_ID,1,2)='" + DropDownList1.SelectedValue.Trim().Substring(0, 2) + "'";
SqlDataAdapter myCommand2 = new SqlDataAdapter(sql2, conn);
DataSet myds2 = new DataSet();
myCommand2.Fill(myds2, "Authors");
DropDownList2.DataSource = myds2.Tables["Authors"].DefaultView;
DropDownList2.DataTextField = "City_Name"; //设置列表显示的字段
DropDownList2.DataValueField = "City_ID"; //设置列表提交后获得的字段
DropDownList2.DataBind();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: