[英]treeview control in asp.net very slow to load nodes
在我的asp.net網頁上,treeview控件具有數千個節點,並且樹的加載速度非常慢。 節點數據使用以下代碼來自sql數據庫。 我們可以做什么來優化或改善性能。
public partial class TaxonomyAllTermsTree : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.AddNodes(this.TreeView1.Nodes, 0, this.LoadData());
TreeView1.CollapseAll();
}
}
private void AddNodes(TreeNodeCollection nodes, int level, System.Data.DataTable dt)
{
string filterExp = string.Format("ParentID='{0}'", level);
foreach (System.Data.DataRow r in dt.Select(filterExp))
{
TreeNode item = new TreeNode()
{
Text = r[2].ToString(),
Value = r[1].ToString(),
NavigateUrl = "SomeURL.aspx?TermID=" + r[0].ToString()
};
this.AddNodes(item.ChildNodes, int.Parse(r[0].ToString()), dt);
nodes.Add(item);
}
}
private System.Data.DataTable LoadData()
{
DataTable dt = new DataTable();
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ThesaurusConnectionString"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand cmd = new SqlCommand("GetFullTree", connection);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
return dt;
}
}
}
1)作為由@Azhar提到設置ExpandDepth為0
ExpandDepth
獲取或設置首次顯示TreeView控件時擴展的級別數。
2)使用ASP.NET緩存在一段時間內將DataTable存儲在緩存中,以避免不必要的數據庫行程,這絕對會提高性能。
以下是一些有關緩存的有用文章:
這是一個例子
//The item will be in the cache for 10 minutes
DataTable table = LoadData();
Cache.Insert("TreeView", table, null, DateTime.Now.AddMinutes(10), TimeSpan.Zero);
檢查密鑰是否存在於高速緩存中,是否確實從高速緩存中加載數據,否則從數據庫中加載數據並將其插入高速緩存中:
if (Cache["TreeView"] != null)
{
var table = Cache["TreeView"] as DataTable;
//Do something with the DataTable
}
else
{
DataTable table = LoadData();
Cache.Insert("TreeView", table, null, DateTime.Now.AddMinutes(1), TimeSpan.Zero);
}
希望這些例子對您有所幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.