遍历、生成 TreeView
1.遍历TreeView
调用 GetAllNode(TreeView.Nodes);
private void GetAllNode(TreeNodeCollection tnc)
{
foreach (TreeNode tn in tnc)
{
tn.Text = tn.Text + "1";
GetAllNode(tn.ChildNodes);
}
}
2.生成TreeView
private DataView dataView;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
dataView = GetCategory();//获取 所有 类别
BindView(this.tv.Nodes[0].ChildNodes,"0");
}
private void BindView(TreeNodeCollection tnc, string CId)
{
DataView dv = this.dataView;
dv.RowFilter = "ParentId = " + CId;//得到某个类别的子类
DataTable dt = dv.ToTable();
if (dt != null && dt.Rows.Count > 0)
{
TreeNode Node = null;
foreach (DataRow row in dt.Rows)
{
string CategoryId = row["CategoryId"] != null ? row["CategoryId"].ToString() : string.Empty;
if (CategoryId != string.Empty)
{
Node = new TreeNode();
tnc.Add(Node);
BindView(Node.ChildNodes, CategoryId);
}
}
}
}
3. 把 TreeView 所有的层次关系记录到数据库中
declare
@CategoryId int,
@ParentId int,
@CurrCategroyId int
declare myCursor cursor for select CategoryId, ParentId from t_newcategory
open myCursor
fetch next from myCursor into @CategoryId, @ParentId
while @@fetch_status = 0
begin
if @@error <> 0 break
begin
-- 插入到辅助查询表中
insert into T_CategorySearch(ParentId, LeafageId)
values(@CategoryId,@CategoryId)
select @CurrCategroyId = @ParentId
while(@CurrCategroyId > 0)
begin
insert into T_CategorySearch(ParentId,LeafageId)
values(@CurrCategroyId,@CategoryId)
if exists
(
select ParentId from t_newcategory where categoryid = @CurrCategroyId
)
begin
select @CurrCategroyId = ParentId from t_newcategory where categoryid = @CurrCategroyId
end
else
begin
set @CurrCategroyId = 0
end
end
end
fetch next from myCursor into @CategoryId, @ParentId
end
close myCursor
deallocate myCursor
表:
CategoryId(类别ID) Name ParentId(父类ID)







评论排行榜