最近我在用treeview+自定义SiteMapDataSource控件读取数据库数据做导航列。

来源:互联网 发布:没有更新到数据库 编辑:程序博客网 时间:2024/05/17 04:20
最近我在用treeview+自定义SiteMapDataSource控件读取数据库数据做导航列。
如不消除本页面已有的参数,试一下在自定义SiteMapDataSource控件的 BuildSiteMapRecurse 方法
给string url添加你的参数
HttpContext context = new HttpContext();
context.Request.QueryString....添加参数。

我的代码如下:
C# code
<asp:TreeView id="treeCategories" ImageSet="Msdn" DataSourceID="srcSiteMap" AutoGenerateDataBindings="false" SelectedNodeStyle-BackColor="#CCCCCC" Runat="server" OnDataBound="treeCategories_DataBound"> <DataBindings> <asp:TreeNodeBinding TextField="Title" ValueField="Key" SelectAction="Select" /> </DataBindings> </asp:TreeView><asp:SiteMapDataSource id="srcSiteMap" StartingNodeUrl="~/Products.aspx" Runat="server" />


自定义SiteMapDataSource控件:
C# code
using System;using System.Collections.Specialized;using System.Web.Configuration;using System.Data;using System.Data.SqlClient;using System.Web;using System.Web.Caching;namespace AspNetUnleashed{ /// <summary> /// Returns Site Map from database /// </summary> public class CategorySiteMapProvider : StaticSiteMapProvider { private bool _isInitialized = false; private SiteMapNode _rootNode; private string _connectionString; private string _navigateUrl; private string _idFieldName; /// <summary> /// Loads configuration settings from Web configuration file /// </summary> public override void Initialize(string name, NameValueCollection attributes) { if (_isInitialized) return; base.Initialize(name, attributes); // Get database connection string from config file string connectionStringName = attributes["connectionStringName"]; if (String.IsNullOrEmpty(connectionStringName)) throw new Exception("You must provide a connectionStringName attribute"); _connectionString = WebConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString; if (String.IsNullOrEmpty(_connectionString)) throw new Exception("Could not find connection string " + connectionStringName); // Get navigateUrl from config file _navigateUrl = attributes["navigateUrl"]; if (String.IsNullOrEmpty(_navigateUrl)) throw new Exception("You must provide a navigateUrl attribute"); // Get idFieldName from config file _idFieldName = attributes["idFieldName"]; if (String.IsNullOrEmpty(_idFieldName)) _idFieldName = "id"; _isInitialized = true; } /// <summary> /// Retrieve the root node by building the Site Map /// </summary> protected override SiteMapNode GetRootNodeCore() { HttpContext context = HttpContext.Current; return BuildSiteMap(); } /// <summary> /// Resets the Site Map by deleting the /// root node. This causes the BuildSiteMap() /// method to rebuild the Site Map /// </summary> public void ResetSiteMap() { _rootNode = null; } /// <summary> /// Build the Site Map by retrieving /// records from database table /// </summary> /// <returns></returns> public override SiteMapNode BuildSiteMap() { // Only allow the Site Map to be created by a single thread lock (this) { if (_rootNode == null) { // Show trace for debugging HttpContext context = HttpContext.Current; HttpContext.Current.Trace.Warn("Loading category site map from database"); // Clear current Site Map Clear(); // Load the database data DataTable tblSiteMap = GetSiteMapFromDB(); // Get the root node _rootNode = GetRootNode(tblSiteMap); AddNode(_rootNode); // Build the child nodes BuildSiteMapRecurse(tblSiteMap, _rootNode); } return _rootNode; } } /// <summary> /// Load the contents of the database table /// that contains the Site Map /// </summary> private DataTable GetSiteMapFromDB() { string selectCommand = "SELECT Id,ParentId,Title,Description FROM Categories"; SqlDataAdapter dad = new SqlDataAdapter(selectCommand, _connectionString); DataTable tblSiteMap = new DataTable(); dad.Fill(tblSiteMap); return tblSiteMap; } /// <summary> /// Get the root node from the DataTable /// </summary> private SiteMapNode GetRootNode(DataTable siteMapTable) { DataRow[] results = siteMapTable.Select("ParentId IS NULL"); if (results.Length == 0) throw new Exception("No root node in database"); DataRow rootRow = results[0]; return new SiteMapNode(this, rootRow["Id"].ToString(), _navigateUrl, rootRow["title"].ToString(), rootRow["description"].ToString()); } /// <summary> /// Recursively build the Site Map from the DataTable /// </summary> private void BuildSiteMapRecurse(DataTable siteMapTable, SiteMapNode parentNode) { DataRow[] results = siteMapTable.Select("ParentId=" + parentNode.Key); foreach (DataRow row in results) { string url = String.Format("{0}?{1}={2}", _navigateUrl, _idFieldName, row["id"]); SiteMapNode node = new SiteMapNode(this, row["Id"
].ToString(), url, row["title"].ToString(), row["description"].ToString());
                AddNode(node, parentNode);
                BuildSiteMapRecurse(siteMapTable, node);
            }
        }

    }
}
导航地图:
C# code
<?xml version="1.0" encoding="utf-8" ?><siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" > <siteMapNode url="~/default.aspx" title="Home " description="Home page"> <siteMapNode provider="CategorySiteMapProvider" /> <siteMapNode url="~/shoppingcart.aspx" title="Shopping Cart" description="View Shopping Cart" /> <siteMapNode url="~/contactinfo.aspx" title="Contact Us" description="Contact us by phone or email" /> <siteMapNode siteMapFile="~/manage/web.sitemap" /> </siteMapNode></siteMap>