zoukankan      html  css  js  c++  java
  • 从DB中读取数据到TreeView中

    有2张表,结构如下:
    表province结构:province_id   province_name   ( primary key:province_id)
    表city结构:city_id,city_name,province_id       (primary key:city_id,province_id)
            SqlConnection conn = new SqlConnection("server=zzy;integrated security=sspi;database=test");
            SqlDataAdapter da;
            DataSet ds 
    = new DataSet();
            
    private void Form1_Load(object sender, EventArgs e)
            {
                readNodes();
                
    this.treeView1.ExpandAll();
            }
            
    private void readNodes()
            {
                
    string _sql = "select * from province";
                da 
    = new SqlDataAdapter(_sql, conn);
                da.Fill(ds, 
    "province");
                DataView dvw1 
    = new DataView(ds.Tables["province"]);
                
    int i = 0;
                
    foreach (DataRowView myRow1 in dvw1)
                {
                    
    string strProvinceName = myRow1["province_name"].ToString().Trim();
                    
    this.treeView1.Nodes.Add(new TreeNode(strProvinceName));//read ParentNode
      
    //---------------------------------------------------------------------------------------------------------------------------------------//
                    da = new SqlDataAdapter("select * from city where province_id='"+myRow1["province_id"].ToString().Trim()+"'",conn);
                    da.Fill(ds,
    "city");
                    DataView dvw2 
    = new DataView(ds.Tables["city"]);
                    
    foreach (DataRowView myRow2 in dvw2)
                    {
                        
    string strCityName = myRow2["city_name"].ToString().Trim();
                        
    this.treeView1.Nodes[i].Nodes.Add(new TreeNode(strCityName));//read ChildNode
                    }
                    i
    ++;
                    ds.Tables[
    "city"].Clear();
                    
    this.treeView1.SelectedNode = treeView1.Nodes[0];
                }
            }


    结果如下:


    备注:以上代码所展示的TreeView只支持2层树结构(跟我测试的Table结构有关),方法比较原始,呵呵,若要扩展可以通过递归调用来实现树型结构的结点读取!
  • 相关阅读:
    《30天自制操作系统》06_day_学习笔记
    《30天自制操作系统》05_day_学习笔记
    《30天自制操作系统》04_day_学习笔记
    ugui Event.current.mousePosition获取的坐标原点在左上角
    场景中GameObject无法用代码隐藏问题(setActive为false)
    让camera实现类似cs第一人称视角旋转和位移
    itunesconnect如何提交被决绝过了的相同版本号
    mac下安装libpng环境
    golang实现模拟键盘按键
    cocos2d3.x在android下屏蔽多点触控
  • 原文地址:https://www.cnblogs.com/perfect/p/577894.html
Copyright © 2011-2022 走看看