最近在用asp.net开发应用程序,发现里面的treeview控件和winfrom里的用发不一样!
所以把自己的心的那来和大家分享下;
asp.net2.0 TreeView:
页面代码:Tree.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Tree.aspx.cs" Inherits="GoodsType_Tree" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>树结构</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TreeView ID="TreeView1" runat="server" ShowLines="True">
</asp:TreeView>
</div>
</form>
</body>
</html>
C#代码 Tree.aspx.cs
private void InitTree()
{
DBAccess access = new DBAccess();
string sql = "select * from type";
DataTable dt = access.GetTable(sql);//此处调用了获的dt的代码,不加入了,自己写.
DataView dv = new DataView(dt);
dv.RowFilter = "父编号=0";
TreeView1.ShowCheckBoxes = TreeNodeTypes.All;
foreach (DataRowView drv in dv)
{
TreeNode node = new TreeNode();
node.Text = drv["类型名称"].ToString();
node.Value = drv["类型编号"].ToString();
node.Expanded = false;
TreeView1.Nodes.Add(node);
AddReplies(dt, node);
}
}
private void AddReplies(DataTable dt, TreeNode node)
{
DataView dv = new DataView(dt);
dv.RowFilter = "父编号='" + node.Value + "'";
foreach (DataRowView row in dv)
{
TreeNode replyNode = new TreeNode();
replyNode.Text = row["类型名称"].ToString();
replyNode.Value = row["类型编号"].ToString();
replyNode.Expanded = false;
node.ChildNodes.Add(replyNode);
AddReplies(dt, replyNode);
}
}
数据库:type表
类型编号 类型名称 父编号
1 啊 0
2 hhh 0
3 www 0
4 yyyyy 2
数据自己加入,不写了.
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/hkdeaccp/archive/2007/11/27/1904593.aspx