treeView绑定省市联动-实习第一天日记

  private void BindTreeView()
        {
            //创建代表省市地区的三个节点
            TreeNode parentnode;
            TreeNode childnode;
             TreeNode townnode;

 

            string constr = "Data Source=(Local);Database=yang;uid=sa;pwd=sa";
            SqlConnection con = new SqlConnection(constr);
            con.Open();
            SqlDataAdapter da = new SqlDataAdapter("select * from province",con);
            DataSet ds = new DataSet();
            da.Fill(ds,"sheng");

 

            foreach(DataRow parentrow in ds.Tables["sheng"].Rows)
            {
                //实例化省节点,第一个参数是节点显示的名称,第二个是对应的ID值(不显示的),第三个是ImageList图片中的图片的索引值
                parentnode = new TreeNode(parentrow["name"].ToString(),Convert.ToInt32(parentrow["code"].ToString()),1);
              
                //将节点添加到树上咯
                treeView1.Nodes.Add(parentnode);

                //查找该省对应有没有市
                SqlDataAdapter da2 = new SqlDataAdapter("select * from city where provinceId='"+parentrow["code"].ToString()+"'",con);
                DataSet ds2 = new DataSet();
                da2.Fill(ds2,"shi");
                if(ds2.Tables["shi"].Rows.Count>0)
                {
                  foreach(DataRow childrow in ds2.Tables["shi"].Rows)
                  {
                      childnode = new TreeNode(childrow["name"].ToString(),Convert.ToInt32(childrow["code"].ToString()),2);
                     
                      //将对应的市添加到该省的节点下
                      parentnode.Nodes.Add(childnode);


                      //查找该市对应有没有地区
                      SqlDataAdapter da3 = new SqlDataAdapter("select * from area where cityId='"+childrow["code"].ToString()+"'",con);
                      DataSet ds3 = new DataSet();
                      da3.Fill(ds3,"diqu");

                      if(ds3.Tables["diqu"].Rows.Count>0)
                      {
                       foreach (DataRow diqurow in ds3.Tables["diqu"].Rows)
                       {
                           townnode = new TreeNode(diqurow["name"].ToString(),Convert.ToInt32(diqurow["code"].ToString    ()),3);
                          
                           //将对应的地区添加到该市节点下
                           childnode.Nodes.Add(townnode);
                       }
                          ds3.Tables["diqu"].Clear();
                      }
                  }

                    ds2.Tables["shi"].Clear();
                }
            }
        }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值