[英]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.