TreeView和数据库绑定

在网上看了天轰穿老师的TreeView这一节课,他讲的很简单,代码如下:
数据库结构:第一个表是big,第二个表是class
TreeView和数据库绑定
代码如下:
privatevoidForm2_Load(objectsender,EventArgse)
{
DataViewdv
=drv("selectbid,titlefrombig");
TreeNoden
=newTreeNode();
n.Text
="中国地区";
this.treeView1.Nodes.Add(n);

foreach(DataRowViewdatavindv)
{
TreeNodetn
=newTreeNode();
tn.Text
=datav["title"].ToString();
tn.Tag
=datav["bid"];
n.Nodes.Add(tn);
AddChildNodes(tn);

}

//ExpandNode(this.treeView1.Nodes);
}

privateDataViewdrv(stringsql)
{
SqlConnectioncon
=newSqlConnection("server=.;database=test;uid=sa;pwd=;");
SqlDataAdaptersda
=newSqlDataAdapter(sql,con);
DataTabledt
=newDataTable();
sda.Fill(dt);
returndt.DefaultView;
}

privatevoidAddChildNodes(TreeNodet)
{
intbid=Convert.ToInt32(t.Tag.ToString());
DataViewd
=drv("select*fromclasswherebid="+bid);
foreach(DataRowViewdatavind)
{
TreeNodenode
=newTreeNode();
node.Text
=datav["title"].ToString();
node.Tag
=datav["cid"];
t.Nodes.Add(node);
}
}
/*
privatevoidExpandNode(TreeNodeCollectiontnc)
{
foreach(TreeNodenodeintnc)
{
node.Expand();
ExpandNode(node.Nodes);
}
}
*/

可是我在做项目时需要根据一个表中的数据来显示树形目录,数据库结构如下:
TreeView和数据库绑定
构件树形目录的方法如下:
#region构建TreeView

publicboolBuildTree(TreeViewtv,DataSetds)
{
tv.Nodes.Clear();

foreach(DataRowdbRowinds.Tables[0].Rows)
{
if(dbRow["FatherNumber"].ToString()==string.Empty)
{
dbRow[
"FatherNumber"]=DBNull.Value;
}
}
ds.Relations.Add(
"NodeRelation",ds.Tables[0].Columns["TypeNumber"],ds.Tables[0].Columns["FatherNumber"],false);

foreach(DataRowdbRowinds.Tables[0].Rows)
{
if(dbRow.IsNull("FatherNumber"))
{
TreeNodenewNode
=CreateNode(dbRow["TypeName"].ToString(),dbRow["TypeNumber"].ToString());

tv.Nodes.Add(newNode);
PopulateSubTree(dbRow,newNode);
}
}

//展开所有节点
tv.ExpandAll();

returntrue;
}

privatevoidPopulateSubTree(DataRowdbRow,TreeNodenode)
{
foreach(DataRowchildRowindbRow.GetChildRows("NodeRelation"))
{
TreeNodechildNode
=CreateNode(childRow["TypeName"].ToString(),childRow["TypeNumber"].ToString());
node.Nodes.Add(childNode);
PopulateSubTree(childRow,childNode);
}
}

privateTreeNodeCreateNode(stringtext,stringtag)
{
TreeNodenode
=newTreeNode();
node.Text
=text;
node.Tag
=tag;
returnnode;
}

这样调用:

SqlConnectioncon=newSqlConnection("server=192.168.1.192;database=AUDE_KCGL;uid=sa;pwd=;");
SqlDataAdaptersda
=newSqlDataAdapter("selectTypeNumber,FatherNumber,TypeNamefromKC_ObjectType",con);
DataSetdsTree
=newDataSet();
sda.Fill(dsTree);
//调用方法构件树形目录
BuildTree(this.treeView1,dsTree);


程序运行效果:
TreeView和数据库绑定

你可能感兴趣的:(数据结构,sql,sql,server)