LINQ绑定TreeView

本文介绍了一个基于ASP.NET的图书分类系统实现方法,通过前台界面展示图书分类,并使用后台逻辑进行数据绑定及子节点递归加载。文章还详细解释了如何通过递归函数获取所选节点的所有上级节点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前台:

<table cellpadding="5" cellspacing="0" style="border:1px; width:100%;" >
<tr >
<td style="width:70%;">
<asp:TreeView ID="TreeView1" runat="server" ExpandDepth="0"
onselectednodechanged="TreeView1_SelectedNodeChanged">
</asp:TreeView>
<asp:Label ID="Label1" runat="server"></asp:Label>
<asp:Label ID="Label2" runat="server"></asp:Label>
</td>

</tr>
</table>

后台:

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
//绑定图书分类树
protected void BindData()
{
BookClassificationBusiness bcb = new BookClassificationBusiness();
var aa = bcb.GetBookClassification();
if (aa.Any())
{
foreach (var a in aa)
{
TreeNode node = new TreeNode();
node.Text = a.ClassificationName;
node.Value = Convert.ToString(a.Childid);
TreeView1.Nodes.Add(node);
BindChildData(node, a.Childid);
}
}
}
//绑定子节点
protected void BindChildData(TreeNode tn,int parentid)
{
BookClassificationBusiness bcb = new BookClassificationBusiness();
var bb = bcb.GetChildBookClass(parentid);
if (bb.Any())
{
foreach (var b in bb)
{
TreeNode Cnode = new TreeNode();
Cnode.Text =b.ClassificationName;
Cnode.Value = Convert.ToString(b.Childid);
tn.ChildNodes.Add(Cnode);
BindChildData(Cnode, b.Childid);
}
}
}
//取得父节点文字
protected void GetParentName(TreeNode tn)
{
if (tn.Parent != null)
{
Label1.Text += "-" + tn.Parent.Text;
Label2.Text += "," + tn.Parent.Value;
GetParentName(tn.Parent);
}
}
//反转字符串
protected string TurnString(string str,char c)
{
string[] aa = str.Split(c);
string bb = "";
for (int i = aa.Length - 1; i > 0; i--)
{
bb += aa[i] + c;
}
bb += aa[0];
return bb;
}
//得到图书分类字符串

protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
{
Label1.Text = TreeView1.SelectedNode.Text;
Label2.Text = TreeView1.SelectedNode.Value;
GetParentName(TreeView1.SelectedNode);
Label1.Text = TurnString(Label1.Text, '-');
Label2.Text = TurnString(Label2.Text, ',');
}

数据库设计:

ChildId ParentID ClassName

业务逻辑层:

public IQueryable<COM_BookClassification> GetBookClassification()
{
CCPressDataContext cp = new CCPressDataContext();
var aa = from a in cp.COM_BookClassification
where a.Parentid==0
select a;
return aa;
}

说明:根目录的id固定为0;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值