数据模型:NewsCategory
Cateid |
uniqueidentifier |
ID |
CateName |
Nvarchar(256) |
分类名 |
PreCate |
uniqueidentifier |
父类 |
IsLeaf |
bit |
是否为叶子 |
首先创建Linq to sql classes文件DB.dbml,把该表拖进去
下面是代码:
在页面上放:
<asp:TreeView ID="TreeView1" runat="server" ShowLines="True">
</asp:TreeView>
.cs中为:
DBDataContext ctx = new DBDataContext();
protected void Page_Load(object sender, EventArgs e)
{
IQueryable<NewsCategory> cates = from cate in ctx.NewsCategories
where cate.PreCate.ToString().Equals("root")
select cate;
foreach (var cate in cates)
{
TreeNode node = new TreeNode();
node.Text = cate.CateName;
node.Value = cate.CateId.ToString();
TreeView1.Nodes.Add(node);
if (cate.IsLeaf==false)
{
node.Expanded = true;
AddReplies(node);
}
}
}
private void AddReplies(TreeNode node)
{
IQueryable<NewsCategory> cs = from c in ctx.NewsCategories
where c.PreCate.ToString().Equals(node.Value)
select c;
foreach (var c in cs)
{
TreeNode replyNode = new TreeNode();
replyNode.Text = c.CateName;
replyNode.Value = c.CateId.ToString();
node.ChildNodes.Add(replyNode);
if (c.IsLeaf==false)
{
replyNode.Expanded = true;
AddReplies(replyNode);
}
}
}