C# 省市地三级联动

C# 省市地三级联动
首先使用VS建立一个ASP.NET空网站,进入项目中添加web窗体;在Default.aspx页面拉入控件如下:

<body>
    <form id="form1" runat="server">
        <div>
            <asp:DropDownList ID="ddlpro" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlpro_SelectedIndexChanged" >
                <asp:ListItem Value="0">请选择</asp:ListItem>
            </asp:DropDownList>
            <asp:DropDownList ID="ddlcity" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlcity_SelectedIndexChanged" >
                <asp:ListItem Value="0">请选择</asp:ListItem>
            </asp:DropDownList>
            <asp:DropDownList ID="ddldis" runat="server">
                <asp:ListItem Value="0">请选择</asp:ListItem>
            </asp:DropDownList>
        </div>
    </form>
</body>

点击设计页面双击选择的下拉框;进入代码页面
页面先首次加载;(!IsPostBack中的代码表示第一次打开这个页面的时候要做的事,一般做一些初始化的事情)
(!this.Page.IsPostBack)中的代码只执行一次,页面重新刷新的话该语句是不执行的
然后开始连接数据库

public string sjk
=“server=.;database=sjk;uid=sa;pwd=localhost”;
开始编辑省份的代码:

 public  void sbd()
    {
        SqlConnection conn = new SqlConnection(sjk);//连接数据库;
        string sql = "select * from S_Province";
        SqlDataAdapter sda=new SqlDataAdapter (sql,conn);
        DataSet ds = new DataSet();
        sda.Fill(ds);
        ddlpro.DataSource = ds;
        ddlpro.DataTextField = "ProvinceName";
        ddlpro.DataValueField = "ProvinceID";
        ddlpro.DataBind();
        ddlpro.Items.Insert(0, new ListItem("请选择", "0"));

    }

接下来双击省份的下拉框进入代码页面编写城市的代码块

  protected void ddlpro_SelectedIndexChanged(object sender, EventArgs e)
    {
        int  id=Convert.ToInt32(ddlpro.SelectedValue);
        SqlConnection conn = new SqlConnection(sjk);
        string sql = "select * from S_City where ProvinceID=" + id + "";
        SqlDataAdapter sda = new SqlDataAdapter(sql, conn);
        DataSet ds = new DataSet();
        sda.Fill(ds);
        ddlcity.DataSource = ds;
        ddlcity.DataTextField = "CityName";
        ddlcity.DataValueField = "CityID";
        ddlcity.DataBind();
        ddlcity.Items.Insert(0, new ListItem("请选择", "0"));
    }

接下来双击城市的下拉框编辑地区的代码块,如下

protected void ddlcity_SelectedIndexChanged(object sender, EventArgs e)
    {
        int id = Convert.ToInt32(ddlcity.SelectedValue);
        SqlConnection conn = new SqlConnection(sjk);
        string sql = "select * from S_District where CityID=" + id + "";
        SqlDataAdapter sda = new SqlDataAdapter(sql, conn);
        DataSet ds = new DataSet();
        sda.Fill(ds);
        ddldis.DataSource = ds;
        ddldis.DataTextField = "DistrictName";
        ddldis.DataValueField = "DistrictID";
        ddldis.DataBind();
        ddldis.Items.Insert(0, new ListItem("请选择", "0"));
    }

此时我们就完成了省市地三级联动,结果如图所示C# 省市地三级联动_第1张图片

你可能感兴趣的:(asp.net,省市地三级联动,c#,数据库,asp.net)