天天看點

第十講 TreeView無限級分類

主要内容

    Page_Load事件中有代碼,建議使用使用Page.IsPostBack

    掌握TreeView動态加載資料的兩種實作方式

        資料綁定介紹

        1. 嵌套循環(不建議)

            執行個體操作

        public void Nodes()

        {

            //擷取省份資訊

            string provinceSql = "select * from Province";

            DataSet ds = DBHelper.ExecuteDataSet(provinceSql, "province");

            foreach (DataRow row in ds.Tables["province"].Rows)

            {

                //建立節點對象

                TreeNode tn = new TreeNode();

                tn.Text = row["Name"].ToString();//設定省節點名稱

                //接下來處理子節點

                string citySql = "select * from City where ProvinceID="+Int32.Parse(row["ProvinceID"].ToString());

                DataSet cityDS = DBHelper.ExecuteDataSet(citySql, "city");

                foreach (DataRow r in cityDS.Tables["city"].Rows)

                {

                    TreeNode cityNode = new TreeNode();

                    cityNode.Text = r["Name"].ToString();//設定城市節點名

                    tn.ChildNodes.Add(cityNode);//将子節點添加到對應省份中

                }

                //最後将省資訊添加到樹上去

                TreeView1.Nodes.Add(tn);

            }

        }

        缺點:是如果需要在子節點下面再添加孫節點時,就需要修改代碼再嵌套循環,如果層級多的話,代碼也同樣會變得複雜。

        為了解決這個問題,就有了下面的遞歸方式:

        2. 遞歸加載,無限級。。。(常用的一種方法,重點推薦)

            執行個體操作

        protected void Page_Load(object sender, EventArgs e)

        {

            string sql = "select * from Nodes";

            DataSet dsNode = DBHelper.ExecuteDataSet(sql, "n");

            Session["node"] = dsNode;

            InitTree(this.TreeView1.Nodes, "0");

        }

        public void InitTree(TreeNodeCollection tnc, string  i)

        {

            DataView dv = new DataView();

            dv.Table = (Session["node"] as DataSet).Tables["n"];

            dv.RowFilter = "Classes=" + i;

            foreach (DataRowView drv in dv)

            {

                TreeNode tn = new TreeNode();

                tn.Value = drv["id"].ToString();

                tn.Text = drv["Name"].ToString();

                tnc.Add(tn);

                InitTree(tn.ChildNodes, tn.Value);

            }

        }