程 序 人 生

[每个人都是工程师,书写着属于自己的人生代码!--林海]
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

用DataTable绑定TreeView的方法

Posted on 2006-10-20 11:02  林海  阅读(2960)  评论(1编辑  收藏  举报

用DataTable绑定TreeView的方法:

  1. 从数据库读取含父子关系列的表并填充到DataSet里去
  2. 创建一个关白联,并为DataSet添加该关联,DataSetNested属性必需为true.
  3. 取得该DataSet的XML描述,用XSLT将XML规则化.
  4. 绑定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();