来源:流星之家
用TreeView生成无限级分类的树型目录:
一、数据库设计
BBS_BestArticleFolder 精华区目录表
| ||||
Key: FolderID
| ||||
Field name | Type | Length | Default | Description |
FolderID | int | 4 |
| ID(自动编号) |
ParentFolderID | int | 4 | 0 | 父目录ID |
FolderName | Nvarchar | 80 |
| 目录名 |
BoardID | int | 4 | 0 | 版块ID |
CreaterUserID | int | 4 | 0 | 创建者ID |
AddTime | DateTime | 8 | GetDate() | 创建时间 |
二、树型目录构建过程
1、安装TreeView控件,我想大多数人都是会安装的,不会安装的去找相关文章一下下。
2、具体实现:
a 数据生成
private DataView CreateDateView(int boardID)
{
BBSBestArticleFolderCollection bafc=new BBSBestArticleFolderCollection();
bafc.GetInfoByParentFolderID(boardID,-1);
int bafcCount=bafc.Count;
DataTable dt = new DataTable("table");
dt.Columns.Add("FolderID",System.Type.GetType("System.String"));
dt.Columns.Add("FolderName",System.Type.GetType("System.String"));
dt.Columns.Add("ParentFolderID",System.Type.GetType("System.String"));
for(int i=0;i<bafcCount;i++)
{
DataRow dr=dt.NewRow();
dr[0]=bafc[i].ID;
dr[1]=bafc[i].FolderName;
dr[2]=bafc[i].ParentFolderID;
dt.Rows.Add(dr);
}
dv=dt.DefaultView;
return dv;
}
#endregion
一点说明:BBSBestArticleFolderCollection对象是个集合类,里面存储了所有符合条件的数据集合,GetInfoByParentFolderID是其中的一个方法,根据一定条件填充集合类的,此文主要讲TreeView构建树型目录,此处会在另外的文章中详述。
b
private void CreateTree(TreeNodeCollection folderTreeNodeCollection ,int parentID)
{ dv.RowFilter= "ParentFolderID="+parentID;
int tmpParentFolderID=0;
foreach(DataRowView drv in dv)
{
TreeNode tn=new TreeNode();
tn.ID=drv.Row["FolderID"].ToString();
tn.Text=drv.Row["FolderName"].ToString().Trim();
tmpParentFolderID=Int32.Parse(drv.Row["ParentFolderID"].ToString().Trim());
//tn.CheckBox=true;
folderTreeNodeCollection.Add(tn);
CreateTree(folderTreeNodeCollection[folderTreeNodeCollection.Count - 1].Nodes,Int32.Parse(tn.ID));
}
}
一点解释:递归构建树的各级节点,其中的dv就是上一个方法生成的DataView
c 取得数据的方法有了,生节节点的方法也有了,那么剩下的就是调用了
CreateTree(TreeView1.Nodes,0);
一点解释:TreeView1是控件ID,这个大家都知道吧,这里的0其实就是表示顶级目录,从顶级目录递归调用下去DI。