SoFunction
Updated on 2025-03-01

Method for implementing on-demand loading in Winform

This article describes the method of implementing on-demand loading in Winform, which is very practical. Share it for your reference. The specific analysis is as follows:

Recently, treeview was used in the project. The original design was to load all data into the treeview from the beginning. Later, I found that the customer's data was too large, and it took 2 minutes to load all data, which was unacceptable to the customer. Later, we considered that the user did not have to look at all the data from the beginning, and the user also expanded layer by layer, so we considered whether it was possible to load the data below the current node when the user expanded a certain node. After searching, I found that the treeview has the BeforeExpand event to achieve our needs.

The specific implementation code is introduced below:

1. First, only the information of each department (node) is loaded

Copy the codeThe code is as follows:
List<string> m_Departments = new List<string>() { "Hubei.Huangshi", "Hubei.Ezhou", "Hubei.Wuhan" };
private void AddDepartMents(List<string> departments)
{
     if (m_Root == null)
     {
         var root = departments[0].Split('.')[0];
         m_Root = new TreeNode(root);
         m_Root.Tag = root;
         (m_Root);
     }
     foreach (var department in departments)
     {
         var parent = m_Root;
         var dts = ('.');
         for (int i = 1; i < ; i++)
         {
             if (!m_OrgNodeManager.ContainsKey(dts[i]))
             {
                 var child = new TreeNode(dts[i],1,1);
                 = dts[i];
                 = department;
                 m_OrgNodeManager.Add(dts[i], child);
                 (child);
                 parent = child;
             }
         }
         ("");
     }
}

Here you should note that after adding each node, you should add an empty sub-node (""); otherwise there will be no plus sign for you to click.

2. Implement BeforeExpand event

Copy the codeThe code is as follows:
private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)
{
     TreeNode curentNode = ;
     if ( == 1)
     {
         ();
         foreach (var user in m_UserManager)
         {
             if (() == ())
             {
                 TreeNode userNode = new TreeNode();
                 (userNode);
             }
         }
     }
}

I hope this article will be helpful to everyone's C# programming.