string ConnString = @"Data Source=.;Initial Catalog=master;Integrated Security=true;"; private DataTable dt = null; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { dt = new DataTable(); GetMenuToDataTable("select * from treeview", dt); BindTree(dt, null, "0"); } } private void BindTree(DataTable dtSource, TreeNode parentNode, string parentID) { DataRow[] rows = dtSource.Select(string.Format("f_ParentNodeId={0}", parentID)); foreach (DataRow row in rows) { TreeNode node = new TreeNode(); node.Text = row["f_Name"].ToString(); node.Value = row["f_NodeId"].ToString(); node.NavigateUrl = row["f_Url"].ToString(); BindTree(dtSource, node, row["f_NodeId"].ToString()); if (parentNode == null) { TreeView1.Nodes.Add(node); } else { 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); ada.Fill(dt); } return dt; }
CREATE TABLE treeview ( f_i_autoid INT IDENTITY(1,1), f_NodeId INT, f_ParentNodeId INT, f_Name VARCHAR(20), f_Tag VARCHAR(20), f_Url NVARCHAR(400), f_order INT , f_isHidden TEXT, f_datetime DATETIME ) INSERT INTO treeview VALUES(1,0,'互联网站','互联网站','#',0,'asdf',GETDATE()) INSERT INTO treeview VALUES(2,1,'百度','互联网站','http://baidu.com',0,'baidu',GETDATE()) INSERT INTO treeview VALUES(3,1,'新浪','互联网站','http://www.sina.com.cn',0,'sina',GETDATE()) INSERT INTO treeview VALUES(4,1,'腾讯','互联网站','http://www.tencent.com',0,'tencent',GETDATE()) INSERT INTO treeview VALUES(5,1,'搜狐','互联网站','http://www.sohu.com',0,'sohu',GETDATE())