asp.net|treeview|数据|数据库
编程思想: 每条记录代表一个节点。通过表里的 2 个数字型的核心字段 f_NodeId、f_ParentNodeId 形成逻辑上的层次型关系。约定 0 代表根节点。其他字段为辅助字段,与本文关系不大。定义和初始化一对象数组 myNodes,然后一次性读取表中的记录,通过判断当前节点的父节点,依次建立所有的上下级关系。示例数据:运行结果:示例下载:http://www.why100000.com/_ftps/samples/Tree+db.rar(代码调试环境:Visual Web Developer 2005 Express Edition)Access数据库名:db_system.mdb表名:tabItems表结构: f_i_autoid 自动编号 f_NodeId 数字(本节点ID) f_ParentNodeId 数字(父节点ID) f_Name 文本 f_Tag 文本 f_Url 文本 f_order 数字 f_isHidden 文本 f_datetime 日期/时间
关键代码:using System;using System.Data;using System.Data.OleDb;using System.Configuration;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;
public partial class _Default : System.Web.UI.Page{ protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string sDbPath = "./db_system.mdb"; //" string sPassword = ""; string sDbTable = "tabItems"; OleDbConnection oConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath(sDbPath) + ";Password=" + sPassword + ";"); OleDbDataReader oDr;
try { oConn.Open(); OleDbCommand oCmd = new OleDbCommand("select * from " + sDbTable, oConn); // + " order by f_level" oDr = oCmd.ExecuteReader();
//定义对象数组 TreeNode[] myNodes = new TreeNode[100];
//初始化对象数组 for (int i = 0; i < myNodes.Length; i++) { myNodes[i] = new TreeNode(); }
//从表中取数据 while (oDr.Read()) { int iParentNodeId = (int)oDr["f_ParentNodeId"]; int iMyNodeId = (int)oDr["f_NodeId"];
if (iParentNodeId != 0) { myNodes[iMyNodeId].Text = oDr["f_name"].ToString(); myNodes[iMyNodeId].NavigateUrl = oDr["f_url"].ToString(); myNodes[iParentNodeId].ChildNodes.Add(myNodes[iMyNodeId]); } else { myNodes[iMyNodeId].Text = oDr["f_name"].ToString(); myNodes[iMyNodeId].SelectAction = TreeNodeSelectAction.None; TreeView1.Nodes.Add(myNodes[iMyNodeId]); } } }
catch (System.Exception sqle) { sqle.ToString().Replace("\n", "<br>"); Response.Write(sqle); } finally { oConn.Close(); }
}
}}