TreeView控件操作开发篇之(二)

继上一遍设置好TreeView的Tag属性后,可以将TreeView保存到DataTable中。方法如下:
       
 #region  TreeView控件数据保存到DataTable
        /// <summary>
        /// TreeView控件数据保存到DataTable
        /// </summary>
        /// <param name="Tv">TreeView控件</param>
        /// <param name="strParentNumberFieldText">父节点编号字段的名称</param>
        /// <param name="strCurrNumberFieldText">当前节点编号字段名称</param>
        /// <param name="strCurrNameFieldText">当前节点Text字段的名称</param>
        /// <returns></returns>
        public DataTable SaveTreeViewToData(TreeView Tv, string strParentNumberFieldText, string strCurrNumberFieldText, string strCurrNameFieldText)
        {
            try
            {
                //定义DataTable
                DataTable DT = new DataTable("HRTree");
                DataColumn DC = new DataColumn(strParentNumberFieldText, typeof(string));
                DC.AllowDBNull = true;
                DC.MaxLength = 10;
                DataColumn DC1 = new DataColumn(strCurrNumberFieldText, typeof(string));
                DataColumn DC2 = new DataColumn(strCurrNameFieldText, typeof(string));
                DT.Columns.Add(DC);
                DT.Columns.Add(DC1);
                DT.Columns.Add(DC2);

                //遍历树
                foreach (TreeNode Node in Tv.Nodes)
                {
                    ForTreeNodeToData(Node, DT);
                }

                return DT;
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 遍历每一个传入的一节点及所有子节点到DataRow中
        /// </summary>
        /// <param name="Node"></param>
        /// <param name="Dt"></param>
        private void ForTreeNodeToData(TreeNode Node,DataTable Dt)
        {
            DataRow DR = null;
            DR = Dt.NewRow();
            if (Node.Parent == null)//所有的一级节点
            {
                DR[0] = "";
            }
            else
            {
                DR[0] = Node.Parent.Tag.ToString();
            }
            DR[1] = Node.Tag.ToString();
            DR[2] = Node.Text;
            Dt.Rows.Add(DR);

            foreach (TreeNode tempNode in Node.Nodes)
            {
                ForTreeNodeToData(tempNode, Dt);
            }

        }
        #endregion


效果图如下:

你可能感兴趣的:(treeview)