用DataTable绑定TreeView的方法:
- 从数据库读取含父子关系列的表并填充到DataSet里去
- 创建一个关白联,并为DataSet添加该关联,DataSet的Nested属性必需为true.
- 取得该DataSet的XML描述,用XSLT将XML规则化.
- 绑定TreeView.
表的内容描述如下:
表名:CATEGORIES | ||
CategoryID |
ParentCategoryID |
CategoryName |
2 |
|
1 |
3 |
|
2 |
4 |
|
3 |
5 |
2 |
1.1 |
6 |
2 |
1.2 |
7 |
2 |
1.3 |
8 |
3 |
2.1 |
9 |
3 |
2.2 |
10 |
4 |
3.1 |
11 |
5 |
1.1.1 |
12 |
5 |
1.1.2 |
13 |
10 |
3.1.1 |
14 |
13 |
3.1.1.1 |
15 |
14 |
3.1.1.1.1 |
16 |
14 |
3.1.1.1.2 |
17 |
14 |
3.1.1.1.3 |
填充DataSet
//Connection to database
OleDbConnection objConn=new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("db.mdb") + ";Persist Security Info=False");
//SQL query to get data from CATEGORIES table
OleDbCommand objCommand=new OleDbCommand("SELECT * FROM CATEGORIES",objConn);
//OleDbDataAdapter
OleDbDataAdapter objDa =new OleDbDataAdapter(objCommand);
//DataSet
DataSet ds=new DataSet("CATEGORIESDS");
//Fill DataSet
objDa.Fill(ds ,"CATEGORIES");
添加关联
//Create DataRelation
DataRelation drel=new
DataRelation("CATEGORIES_RECURSIVE",
ds.Tables["CATEGORIES"].Columns["CategoryID"],
ds.Tables["CATEGORIES"].Columns["ParentCategoryID"]);
//Make sure relation is nested
drel.Nested =true;
//Add relation to DataSet's Relations collection
ds.Relations.Add(drel);
XML转换
//XmlDocument to hold XML generated from DataSet
XmlDocument objDoc=new XmlDocument();
//Load XML
objDoc.LoadXml(ds.GetXml());
//Create XslTransform object
XslTransform objXSL=new XslTransform();
//Load XSLT stylesheet
objXSL.Load(Server.MapPath("transformationtemplate.xslt"));
//StringWriter to temporarily hold result of the transformation
StringWriter writer=new StringWriter();
//Apply transformation with no arguments and dump results to StringWriter.
objXSL.Transform(objDoc.CreateNavigator(),null,writer);
绑定TreeView
//Set TreeView's TreeNodeSrc property to get XML from StringWriter.
TreeView1.TreeNodeSrc =writer.ToString();
//Bind TreeView
TreeView1.DataBind();
//Close StringWriter
writer.Close();