当前位置:首页 > Windows程序 > 正文

C#树目录(treeView)的编写

2021-03-26 Windows程序

1,数据库(DAL层)编写

(1)模板的编写

public class CategoryModel{ public int _CategoryID { get; set; } public string _CategoryName { get; set; } public string _CategoryPy { get; set; } public int _ParentID { get; set; } }

 (2)从数据库中获取集合

//获取类别信息 public List<CategoryModel> GetCategoryDal(int ParentID) { string str = "select * from Category where ParentID=@ParentID"; List<CategoryModel> list = new List<CategoryModel>(); SQLiteParameter[] sqlitePara = { new SQLiteParameter("ParentID",ParentID) }; DbDataReader read= SQLiteHelper.ExecuteReader(str,sqlitePara); while (read.Read()) { if (read.HasRows) { CategoryModel model = new CategoryModel(); model._CategoryID = read.GetInt32(0); model._CategoryName = read.GetString(1); model._CategoryPy = read.GetString(2); model._ParentID = read.GetInt32(3); list.Add(model); } } return list; }

2,,(BLL)层

//获取目录信息 public List<CategoryModel> GetCategoryInfo(int id) { ClassDal dal = new ClassDal(); return dal.GetCategoryDal(id); }

3,树目录的编写

表是这样的

(用到递归的方   private void TreeGetDate(TreeNodeCollection t,int id)

{ ClassBll bll = new ClassBll();//新建BLL层类主要为了调用数据库 List<CategoryModel> list = new List<CategoryModel>(); list = bll.GetCategoryInfo(id);
//
数据库的数据存在这个集合中(上面的为获取指定parentID的数据)
/*
1,第一次传入0;TreeGetDate(TreeView1.Nodes,0);
则list中的数据为等ParentID为0的数据

*/
for (int i = 0; i < list.Count; i++) { string name = list[i]._CategoryName;// int pid = list[i]._CategoryID; TreeNode tree = t.Add(name); tree.Tag = pid;
/*
接着获取Category的值,把值传给下一次循环
如:下一次为132则 调用 TreeGetDate(tree.Nodes,132); 结果就会在tree的子节点上添加
这样的子节点以此类推
*/
tree.ImageIndex
= 0;//显示图片 TreeGetDate(tree.Nodes,pid); } }

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/67927.html