Loading lots of data into a Treeview
Sunday, December 31, 2006
Thought I would post this one.
This just a simple Treeview control that has been inherited from Treeview class . The important factor though is that it allows for a loading alot of data without holding up the main windows Thread. using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.ComponentModel;
namespace UnwindSoftware.UnwindCMS.UnwindAdminTool.AdminControls
{
public class TreeViewProductsAll : System.Windows.Forms.TreeView
{
private BackgroundWorker bgWorker = new BackgroundWorker();
public TreeViewProductsAll()
{
bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorker_RunWorkerCompleted);
}
void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.BeginUpdate();
this.Nodes.Clear();
TreeNode tnMain = (TreeNode)e.Result;
this.Nodes.Add(tnMain);
this.ExpandAll();
this.EndUpdate();
}
void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
ProductListTypedList products = new ProductListTypedList();
//UnwindProductsCollection products = new UnwindProductsCollection();
ISortExpression sorter = new SortExpression(
SortClauseFactory.Create(UnwindProductsFieldIndex.ProductName, SortOperator.Ascending));
products.Fill(100000, sorter);
//products.GetMulti(null, 100000000, sorter);
this.Nodes.Clear();
TreeNode tnMain = new TreeNode("Products");
foreach (ProductListRow prod in products)
{
ProductTreeNode tn = new ProductTreeNode(prod.ProductName, prod.ProductId);
tnMain.Nodes.Add(tn);
}
products.Clear();
products.Dispose();
e.Result = tnMain;
}
//We call this after we have created the constructor.
public void LoadProducts()
{
bgWorker.RunWorkerAsync();
TreeNode tn = new TreeNode("Loading..");
this.Nodes.Add(tn);
}
}
}
What is so cool about .NET 2 is that the windows Background worker thread allows you do this is a very simple fashion. Leading you to easily build windows controls that load quickly and responsively. The above code does not work out of the box I had to strip some of it out, but it should give you a good idea how to implement this in your own controls. I will try and post a more complete example in the coming weeks.


0 Comments:
Post a Comment
<< Home