C# TreeView 控制項的父子節點動態產生

來源:互聯網
上載者:User

       剛申請了一個部落格,今天做論文時 用到分類列表地顯示食物類型和名稱. 決定用 treeview 控制項.

來和大家分享一下,如果您有好的建議請聯絡我.

首先是 : 資料庫 , 表中欄位如下

表1  tb_food                   表2 tb_foodtype

foodType                         foodType

foodName                        typeName

其次是 : 您必須建立一個winfrom 表單 在表單裡添加 TreeView控制項並命名為treeView1

再次是: 在表單的載入事件裡寫Code

 

Code
 1 try
 2            {
 3                SqlConnection con = linkdate.CYGL();//串連資料庫用的 ,請自行設定
 4                SqlCommand cmd = new SqlCommand("select * from tb_foodtype ", con);
 5                con.Open();
 6                SqlDataReader sdr = cmd.ExecuteReader();
 7
 8               
 9                while (sdr.Read())
10                {
11                    TreeNode Pnode = new TreeNode(sdr["typeName"].ToString());
12
13                    treeView1.Nodes.Add(Pnode);// 添加父節點
14                    try
15                    {
16
17                        SqlConnection con0 = linkdate.CYGL();
18                        con0.Open();
19                        SqlCommand cmd1 = new SqlCommand("select * from tb_food where foodType='" + sdr["foodType"].ToString() + "'", con0);
20                        SqlDataReader sdr1 = cmd1.ExecuteReader();
21                        while (sdr1.Read())
22                        {
23                            TreeNode Tnode = new TreeNode(sdr1["foodName"].ToString());
24                            Pnode.Nodes.Add(Tnode);//添加子節點
25                        }
26                        con0.Close();
27                    }
28                    catch (System.Exception exs)
29                    {
30                        MessageBox.Show(exs.Message.ToString());
31                    } 
32                                      
33                 }
34               
35                con.Close();
36            }
37            catch (System.Exception ex)
38            {
39                MessageBox.Show(ex.Message.ToString());
40            }
41          //如有疑問cell me

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.