在网上看了很多,自己为了锻炼一下自己写了一个小的省市的二级联动。运行是可以的,请高手们多指教。
前台页面:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DropDownhoutai.aspx.cs" Inherits="DropDownhoutai" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>DropdownList联动</title>
</head>
<body>
<form id="form1" runat="server">
<div>
省份:<asp:DropDownList ID="ddlProvince" runat="server" OnSelectedIndexChanged="ddlProvince_SelectedIndexChanged" AutoPostBack ="true" ></asp:DropDownList>
市:<asp:DropDownList ID="ddlCity" runat="server"></asp:DropDownList>
</div>
</form>
</body>
</html>
后台页面:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class DropDownhoutai : System.Web.UI.Page
{
static string connString = "server=localhost;database=NationalAll;uid=sa;pwd=123456;";
SqlConnection con = new SqlConnection(connString);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlDataAdapter sda = new SqlDataAdapter("select * from Province", con);
DataSet dt = new DataSet();
sda.Fill(dt);
ddlProvince.DataSource = dt.Tables[0].DefaultView;
ddlProvince.DataTextField = "ProName";
ddlProvince.DataValueField = "ProId";
ddlProvince.DataBind();
ddlProvince.Items.Insert(0, new ListItem("--请选择--", "0"));
ddlCity.Items.Insert(0, new ListItem("--请选择--", "0"));
}
}
protected void ddlProvince_SelectedIndexChanged(object sender, EventArgs e)
{
BindCity(int.Parse(this.ddlProvince.SelectedItem.Value));
}
protected void BindCity(int ProID)
{
SqlCommand command = new SqlCommand("select * from City where ProID=@ProID",con);
command.Parameters.Add(new SqlParameter("@ProID", ProID));
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(command);
da.Fill(ds);
ddlCity.DataSource = ds.Tables[0].DefaultView;
ddlCity.DataTextField = "CityName";
ddlCity.DataValueField = "CityID";
ddlCity.DataBind();
}
}
如果大家有更好的可以回帖,希望大家多给点意见。谢谢!!!!