TreeView控件二(递归算法)
生活随笔
收集整理的這篇文章主要介紹了
TreeView控件二(递归算法)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
擴展了一下。每個控件都有其獨特的寫法和用法,treeview就是這樣的一個控件。做個類似資源管理器的頁面。如果逐層遍歷,代碼會不斷重復,所以這時需要用遞歸算法
?
?
Code?public?static?void?TreeBindMethod(TreeView?tvFile,string?target)
????????{
????????????tvFile.Nodes.Clear();
????????????TreeNode?rootNode?=?new?TreeNode("文件管理",?"0",?"~/Images/file/folder.gif","FileMain.aspx?id=0","");
????????????tvFile.Nodes.Add(rootNode);
????????????IList<FileInfo>?list?=?FileInfoService.GetAllEntities().Where(c=>c.IsDelete==false).ToList();
????????????var?query?=?list.Where(c?=>?c.ParentId?==?0).Select(c?=>?c).ToList();
????????????foreach?(FileInfo?file?in?query)
????????????{
????????????????TreeNode?node?=?GetFileTree(out?target,?file);
????????????????AddChildTree(list,?file,?target,?node);
????????????????AddTreeMethod(rootNode,?node);
????????????}
????????}
????????private?static?string?filename;
????????private?static?TreeNode?GetFileTree(out?string?target,?FileInfo?file)
????????{
????????????TreeNode?node?=?new?TreeNode();
????????????if?(file.FileName.Length?>?8)
????????????{
????????????????filename?=?file.FileName.Substring(0,?7)?+?"";
????????????}
????????????else?{
????????????????filename?=?file.FileName;
????????????}
????????????node.Text?=?filename;
????????????node.Value?=?file.Id.ToString();
????????????node.ImageUrl?=?file.FileType.FileTypeImage;
????????????node.NavigateUrl?=?string.Format("FileMain.aspx?Id={0}",file.Id);
????????????target?=?file.FilePath;
????????????return?node;
????????}
????????private?static?void?AddChildTree(IList<FileInfo>?list,?FileInfo?file,string?target,?TreeNode?fatherNode)
????????{
????????????int?id?=?file.Id;
????????????var?childquery?=?list.Where(c?=>?c.ParentId?==?id).ToList();
????????????foreach?(FileInfo?childfile?in?childquery)
????????????{
????????????????TreeNode?childnode?=?new?TreeNode();
????????????????childnode.Text?=?childfile.FileName;
????????????????childnode.ImageUrl?=?childfile.FileType.FileTypeImage;
????????????????childnode.NavigateUrl?=?string.Format("FileMain.aspx?Id={0}",?childfile.Id);
????????????????target?=?childfile.FilePath;
//這里調用了自己,就是遞歸算法,遍歷了樹所有節點
????????????????AddChildTree(list,?childfile,?target,?childnode);
????????????????AddTreeMethod(fatherNode,?childnode);
????????????}
????????}
????????private?static?void?AddTreeMethod(TreeNode?fatherNode,?TreeNode?childnode)
????????{
????????????fatherNode.ChildNodes.Add(childnode);
????????}
//當然,可以設置一個int?depth=0;的參數,在遞歸算法前,if(depth++>4?yield?break;來設置遞歸深度
?
轉載于:https://www.cnblogs.com/drek_blog/archive/2009/07/12/1522143.html
總結
以上是生活随笔為你收集整理的TreeView控件二(递归算法)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何用distinct消除重复记录的同时
- 下一篇: 《诛仙》动画正式开播:每集结尾竟然有德云