從DB中讀取資料到TreeView中

來源:互聯網
上載者:User
有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結構有關),方法比較原始,呵呵,若要擴充可以通過遞迴調用來實現樹型結構的結點讀取!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.