ASP.Net绑定数据到树[TreeView]-----献给善忘的,依然是菜鸟的我们。
ASP.Net绑定数据到树[TreeView]上的方法
本例提供2种方案,原理一致.
对于返回的list 也同理绑定。
代码如下。--------献给依然是菜鸟的我们
创建表
create table Tree
(
ID int primary key not null,
Title varchar(20) not null,
Url varchar(100) ,
ParentID int not null
)
go
insert into Tree(ID,Title,ParentID)
values(1,'系统设置',-1)
insert into Tree(ID,Title,ParentID)
values(2,'园区管理',-1)
insert into Tree(ID,Title,ParentID)
values(3,'评价管理',-1)
insert into Tree(ID,Title,ParentID)
values(4,'指标管理',-1)
insert into Tree(ID,Title,Url,ParentID)
values(6,'用户维护','User/UserInfo.aspx',1)
insert into Tree(ID,Title,Url,ParentID)
values(7,'角色维护','User/PartInfo.aspx',1)
insert into Tree(ID,Title,Url,ParentID)
values(8,'密码修改','User/ChangPwd.aspx',1)
insert into Tree(ID,Title,Url,ParentID)
values(9,'园区维护','GardenArea/GardenAreaEdit.aspx',2)
insert into Tree(ID,Title,Url,ParentID)
values(10,'联系人维护','GardenArea/GaContact1.aspx',2)
insert into Tree(ID,Title,Url,ParentID)
values(11,'评价维护','CertificationBody/CertificationBody.aspx',3)
insert into Tree(ID,Title,Url,ParentID)
values(12,'联系人维护','CertificationBody/CbContact.aspx',3)
insert into Tree(ID,Title,Url,ParentID)
values(13,'指标维护','Indicators/Indicators.aspx',4)
insert into Tree(ID,Title,Url,ParentID)
values(14,'总评价等级定义','Indicators/DegreeDefine.aspx',4)
insert into Tree(ID,Title,Url,ParentID)
go
页面代码
public void BindData()
{
string connString = "Server=PRODUCT;Database=数据库名;uid=sa;pwd=sa";
SqlConnection sqlcon = new SqlConnection(connString);
SqlDataAdapter da = new SqlDataAdapter("select * from Tree", sqlcon);
DataTable dt = new DataTable();
da.Fill(dt);
// BindTreeView(dt,TreeView1.Nodes,-1);
BindTree(dt, null, -1);
}
public void BindTree(DataTable dt,TreeNode ptn, int pid)
{
DataRow[] drs = dt.Select("ParentID=" + pid);
foreach (DataRow b in drs)
{
TreeNode tn=new TreeNode();
tn.Value = b["ID"].ToString();
tn.Text = b["Title"].ToString();
tn.NavigateUrl = b["Url"].ToString();
if (ptn==null)
{
TreeView1.Nodes.Add(tn);
}
else
{
ptn.ChildNodes.Add(tn);
}
BindTree(dt, tn, Convert.ToInt32(tn.Value));
}
}
private void BindTreeView(DataTable dt, TreeNodeCollection tnc, int pid)
{
DataRow[] drs = dt.Select("ParentID=" + pid);
foreach (DataRow b in drs)
{
TreeNode tn = new TreeNode();
tn.Value = b["ID"].ToString();
tn.Text = b["Title"].ToString();
tn.NavigateUrl = b["Url"].ToString();
tnc.Add(tn);
BindTreeView(dt, tn.ChildNodes, Convert.ToInt32(tn.Value));
}
}
作者:SIR@君
Email:sirjun@foxmail.com
云购:注册立送五元红包,1元也能抢购IPhone啦!