省级联动

本博客展示了如何使用C#连接数据库并执行SQL查询来获取省份和城市数据,通过数据适配器填充数据列表,实现用户友好的交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 
protected void Page_Load(object sender, EventArgs e)
    { 

 if (!IsPostBack)
        {
            

               string str = "server=.;database=exam;Integrated security=true";
                DataSet ds=new DataSet ();
               using (SqlConnection sqlCnn = new SqlConnection(str))
              {
                    using (SqlCommand sqlCmm = new SqlCommand())
                   {
                       sqlCmm.Connection = sqlCnn;
                       sqlCmm.CommandText = "select name,pid from province";
                       SqlDataAdapter da = new SqlDataAdapter(sqlCmm);
                       da.Fill(ds);
                  }
                this.DropDownList1.DataSource = ds.Tables[0];
                this.DropDownList1.DataTextField = "name";
                this.DropDownList1.DataValueField = "pid";

                this.DataBind();

                this.DropDownList1.Items.Insert(0, "--请选择省份--");
                this.DropDownList2.Items.Insert(0, "--请选择城市--");
            }
      }

}

 

 protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        string str = "server=.;database=exam;Integrated security=true";
        DataSet ds = new DataSet();
        using (SqlConnection sqlcnn = new SqlConnection(str))
        {
            SqlCommand sqlcmm = sqlcnn.CreateCommand();
            sqlcmm.CommandText ="select cname,pid from city where pid =" + DropDownList1.SelectedValue;
            SqlDataAdapter sda = new SqlDataAdapter(sqlcmm);
            sda.Fill(ds);
        }
        this.DropDownList2.DataSource = ds.Tables[0];
        this.DropDownList2.DataTextField = "cname";
        this.DropDownList2.DataValueField = "pid";
        this.DataBind();
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值