创建表及插入模拟数据:
CREATE TABLE [sysMenuTree]( |
[NoteId] [ decimal ](18, 0) NOT NULL , |
[ParentId] [ decimal ](18, 0) NULL , |
[sText] [nvarchar](50) NULL , |
[sValue] [nvarchar](50) NULL , |
[sURL] [nvarchar](50) NULL , |
[sTarget] [nvarchar](50) NULL , |
[Chger] [nvarchar](50) NULL , |
[ChgTime] [nvarchar](50) NULL ) |
insert into sysMenuTree values (3,0,N '目錄' ,N '目錄' , '' , '' , '' , '' ) |
insert into sysMenuTree values (4,0,N '目錄' ,N '目錄' , '' , '' , '' , '' ) |
insert into sysMenuTree values (5,0,N '目錄' ,N '目錄' , '' , '' , '' , '' ) |
insert into sysMenuTree values (6,3,N '項目.1' ,N '項目.1' , '' , '' , '' , '' ) |
insert into sysMenuTree values (7,3,N '項目.2' ,N '項目.2' , '' , '' , '' , '' ) |
insert into sysMenuTree values (8,4,N '項目.1' ,N '項目.1' , '' , '' , '' , '' ) |
insert into sysMenuTree values (9,4,N '項目.2' ,N '項目.2' , '' , '' , '' , '' ) |
insert into sysMenuTree values (10,4,N '項目.3' ,N '項目.3' , '' , '' , '' , '' ) |
insert into sysMenuTree values (11,5,N '項目.1' ,N '項目.1' , '' , '' , '' , '' ) |
insert into sysMenuTree values (12,5,N '項目.2' ,N '項目.2' , '' , '' , '' , '' ) |
<form id= "form1" runat= "server" > |
<asp:TreeView ID= "treeMenu" runat= "server" > |
using System.Web.UI.WebControls; |
using System.Data.SqlClient; |
public partial class _Default : System.Web.UI.Page |
private readonly string ConnString = @"server=.\MSSQLSERVER2008;database=chart;uid=sa;pwd=123456" ; |
private DataTable dt = null ; |
protected void Page_Load( object sender, EventArgs e) |
GetMenuToDataTable( "select * from sysMenuTree" ,dt); |
private void BindTree(DataTable dtSource,TreeNode parentNode, string parentID) |
DataRow[] rows = dtSource.Select( string .Format( "ParentID={0}" ,parentID)); |
foreach (DataRow row in rows) |
TreeNode node = new TreeNode(); |
node.Text = row[ "sText" ].ToString(); |
node.Value = row[ "sValue" ].ToString(); |
BindTree(dtSource,node,row[ "NoteId" ].ToString()); |
treeMenu.Nodes.Add(node); |
parentNode.ChildNodes.Add(node); |
private DataTable GetMenuToDataTable( string query,DataTable dt) |
using (SqlConnection conn = new SqlConnection(ConnString)) |
SqlCommand cmd = new SqlCommand(query,conn); |
SqlDataAdapter ada = new SqlDataAdapter(cmd); |
转载于:https://blog.51cto.com/huang1231932/568376