This article briefly describes the implementation of lazy loading in commonly used controls.
1. Load the data when the interface is first displayed. The simplest lazy loading can load data when the control is displayed for the first time. For example, if you have many tabs, the data will only be loaded when the user switches to this tab.
The SetVisibleCore virtual method is provided in .NET Control. When the detected value is true and this method is called for the first time, lazy loading is called. But I don't recommend this method because you have better places.
- If your control inherits from Form or UserControl, it is recommended to overload OnLoad;
- If inherited from Control, OnCreateControl can be overloaded.
Here is an example of lazy loading of data:
public class MyTabPage : TabPage {
protected override void OnCreateControl() {
base.OnCreateControl();
string oldText = this.Text;
this.Text = "Loading..";
//TODO: Call the method of loading data here
this.Text = oldText;
}
}
2. The tree control is loaded when it is expanded for the first time.
Because all nodes in TreeView do not inherit from Control, you cannot use the above method. However, TreeView provides the OnBeforeExpand virtual method. The simplest way is to add a loaded mark to the node you plan to implement delayed loading. When the first During the first expansion, detect this mark.
You must remember that your lazy loading node cannot receive this event at the root location.
3. Lazy loading in tables.
In Windows programs, some use paging to implement lazy loading, but the user experience of this method is very bad. If you still want to use scroll bars, you can implement the IBindList interface yourself, which holds a list of data IDs internally. When the form asks for data, it loads the data in the database. Common table controls can work well.
But there is something that should be noted here. For example, when the user presses PageDown, the table control continuously calls the data acquisition method. If the database is called for every request, the performance will be very low. Your program should be "predicted" to You may have to read 50 pieces of data, so you can read 50 more pieces at once.
This method has no solution when it comes to table sorting.
The above are the general techniques of lazy loading technology. If you have a better method, please enlighten me.