Devexpress WinForm TreeList的三種數據綁定方式(DataSource綁定、AppendNode添加節點、VirtualTreeGetChildNodes(虛擬樹加載模式))


第一種:DataSource綁定,這種綁定方式需要設置TreeList的ParentFieldName和KeyFieldName兩個屬性,這里需要注意的是KeyFieldName的值必須是唯一的。

代碼如下:

 private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                //構建一個DataTable數據源
                DataTable table = new DataTable();
                table.Columns.Add("parentId");
                table.Columns.Add("Id");
                table.Columns.Add("parentName");
                table.Columns.Add("Name");
                DataRow row = table.NewRow();
                row["parentId"] = "";
                row["Id"] = "*";
                row["Name"] = "所有顏色";
                table.Rows.Add(row);
                row = table.NewRow();
                row["parentId"] = "*";
                row["Id"] = "1";
                row["Name"] = "紅色";
                table.Rows.Add(row);
                row = table.NewRow();
                row["parentId"] = "*";
                row["Id"] = "2";
                row["Name"] = "黃色";
                table.Rows.Add(row);
                row = table.NewRow();
                row["parentId"] = "*";
                row["Id"] = "3";
                row["Name"] = "綠色";
                table.Rows.Add(row);
                row = table.NewRow();
                row["parentId"] = "1";
                row["Id"] = "01";
                row["Name"] = "粉紅色";
                table.Rows.Add(row);
                row = table.NewRow();
                row["parentId"] = "2";
                row["Id"] = "02";
                row["Name"] = "鵝黃色";
                table.Rows.Add(row);
                treeList1.ParentFieldName = "parentId";
                treeList1.KeyFieldName = "Id";
                treeList1.DataSource = table;
                treeList1.ExpandAll();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void treeList1_BeforeCheckNode(object sender, DevExpress.XtraTreeList.CheckNodeEventArgs e)
        {
            e.State = (e.PrevState == CheckState.Checked ? CheckState.Unchecked : CheckState.Checked);
        }

        private void treeList1_AfterCheckNode(object sender, DevExpress.XtraTreeList.NodeEventArgs e)
        {
            try
            {
                SetCheckedChildNodes(e.Node, e.Node.CheckState);
                SetCheckedParentNodes(e.Node, e.Node.CheckState);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 設置子節點的狀態
        /// </summary>
        /// <param name="node"></param>
        /// <param name="check"></param>
        private void SetCheckedChildNodes(TreeListNode node, CheckState check)
        {
            for (int i = 0; i < node.Nodes.Count; i++)
            {
                node.Nodes[i].CheckState = check;
                SetCheckedChildNodes(node.Nodes[i], check);
            }
        }

        /// <summary>
        /// 設置父節點的狀態
        /// </summary>
        /// <param name="node"></param>
        /// <param name="check"></param>
        private void SetCheckedParentNodes(TreeListNode node, CheckState check)
        {
            if (node.ParentNode != null)
            {
                bool b = false;
                CheckState state;
                for (int i = 0; i < node.ParentNode.Nodes.Count; i++)
                {
                    state = (CheckState)node.ParentNode.Nodes[i].CheckState;
                    if (!check.Equals(state))
                    {
                        b = !b;
                        break;
                    }
                }
                node.ParentNode.CheckState = b ? CheckState.Checked : check;
                SetCheckedParentNodes(node.ParentNode, check);
            }
        }

運行效果圖:

 第二種:AppendNode添加節點

代碼如下:

 

        private void LoadTree()
        {
            //清空節點
            treeList1.BeginUnboundLoad();
            treeList1.ClearNodes();
            arrayList = new List<TreeListNode>();
            //綁定部位樹樹的第一層
            TreeListNode Node = treeList1.Nodes.Add(new object[] { "所有顏色", "*"});
            Node.Tag = "*";
            arrayList.Add(Node);
            //綁定第二層
            DataSet ds = SqlHelper.Query(@"select ctc.colorId as ParentNodeID,ctc.childcolorId as NodeID, cc.names as NodeName
            from C_colorTocolor ctc(nolock)
            inner join C_color cc(nolock) on ctc.childcolorId=cc.id");
            if (ds != null && ds.Tables.Count > 0)
            {
                table = ds.Tables[0];
                DataRow[] rows = table.Select("ParentNodeID='*'");
                foreach (DataRow row in rows)
                {
                    TreeListNode tn = treeList1.AppendNode(new object[] { row["NodeName"].ToString(), row["NodeID"].ToString() }, Node.Id);
                    tn.Tag = row["NodeID"].ToString();
                    arrayList.Add(tn);
                    BindNode(row["NodeID"].ToString(), tn);
                }
            }
            treeList1.EndUnboundLoad();
            treeList1.ExpandAll();
        }

        private void BindNode(string nodeId, TreeListNode tn)
        {
            DataRow[] rows = table.Select("ParentNodeID='" + nodeId + "'");
            foreach (DataRow row in rows)
            {
                TreeListNode tns = treeList1.AppendNode(new object[] { row["NodeName"].ToString(), row["NodeID"].ToString()}, tn.Id);
                tns.Tag = row["NodeID"].ToString();
                arrayList.Add(tns);
                BindNode(row["NodeID"].ToString(), tns);
            }
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            //綁定樹
            LoadTree();
        }

運行效果圖:

 第三種:VirtualTreeGetChildNodes虛擬樹加載。這種模式主要用於數據量過多,打開界面比較慢的情況。

private void Form3_Load(object sender, EventArgs e)
        {
            //初始化樹
            InitData();
        }

        bool isload = false;
        void InitData()
        {
            isload = false;
            treeList1.ClearNodes();
            treeList1.DataSource = new object();
        }

        private void treeList1_VirtualTreeGetChildNodes(object sender, DevExpress.XtraTreeList.VirtualTreeGetChildNodesInfo e)
        {
            Cursor current = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;
            if (!isload)
            {
                List<O_node> roots = new List<O_node> { new O_node() { id= "*", names= "所有顏色",parentid="" } };
                e.Children = roots;
                isload = true;
            }
            else
            {
                try
                {
                    O_node on = e.Node as O_node;
                    if(on!=null)
                    {
                        string sql = string.Format(@"select ctc.colorId as parentid,ctc.childcolorId as id, cc.names as names
                        from C_colorTocolor ctc(nolock)
                        inner join C_color cc(nolock) on ctc.childcolorId = cc.id
                        where ctc.colorId = '{0}'", on.id);
                        DataSet ds  = SqlHelper.Query(sql);
                        if (ds != null && ds.Tables.Count > 0)
                        {
                            List<O_node> lst = (List<O_node>)DataTableToList<O_node>(ds.Tables[0]);
                            e.Children = lst;
                        }
                        else
                        {
                            e.Children = new object[] { };
                        }
                    }
                    else
                    {
                        e.Children = new object[] { };
                    }
                }
                catch
                {
                    e.Children = new object[] { };
                }
            }
            Cursor.Current = current;
        }

        private void treeList1_VirtualTreeGetCellValue(object sender, DevExpress.XtraTreeList.VirtualTreeGetCellValueInfo e)
        {
            string name = string.Empty;
            if (e.Node is O_node)
            {
                name = (e.Node as O_node).names;
            }
            if (e.Column == treeListColumn1) e.CellData = name;
        }

        public static IList<T> DataTableToList<T>(DataTable table)
            where T : class
        {
            if (!IsHaveRows(table))
                return new List<T>();
            IList<T> list = new List<T>();
            T model = default(T);
            foreach (DataRow dr in table.Rows)
            {
                model = Activator.CreateInstance<T>();
                foreach (DataColumn dc in dr.Table.Columns)
                {
                    object drValue = dr[dc.ColumnName];
                    PropertyInfo pi = model.GetType().GetProperty(dc.ColumnName);
                    if (pi != null && pi.CanWrite && (drValue != null && !Convert.IsDBNull(drValue)))
                    {
                        pi.SetValue(model, drValue, null);
                    }
                }
                list.Add(model);
            }
            return list;
        }

        /// <summary>
        /// 檢查DataTable 是否有數據行
        /// </summary>
        /// <param name="dt">DataTable</param>
        /// <returns></returns>
        public static bool IsHaveRows(DataTable dt)
        {
            if (dt != null && dt.Rows.Count > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }

    #region 節點
    public class O_node
    {
        public string id { get; set; }
        public string names { get; set; }
        public string parentid { get; set; }
    }
    #endregion

運行效果圖:

完整示例代碼:https://download.csdn.net/download/u012026245/11986777

csdn現在資源積分上傳時都是固定積分為5分了,如果需要完整代碼的可以去下載一下。

打賞

免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號  © 2018-2021 CODEPRJ.COM