Sometimes while developing a winform application, we may have to add the items to the list control (ComboBox, ListView, ListBox, TreeView) dynamically. Generally we do this by using Items.Add() method. But there is performance issue related to this. Whenever we add an item to the control, the control immediately repaints itself to reflect the changes. So how many items we will add item to the control, it repaints itself that many number of times. There are few ways by which we can avoid this and save some processing time and maintain the performance. These are as follow:
– Use of AddRange() method: By using this method you can add an array of items to the control in a single operation. The control repaints itself after the operation is done.
Example:
object[] arr = new object[500];
for (int count = 0; count < 500; count++)
{
arr[count] = count;
}
cmbTest.Items.AddRange(arr);
– Use of BeginUpdate() and EndUpdate() methods: We can use the BeginUpdate() method to inform the control not to repaint itself until all the items are added and the EndUpdate() method encountered.
Example:
cmbTest.BeginUpdate();
for (int count = 0; count < 500; count++)
{
cmbTest.Items.Add(count);
}
cmbTest.EndUpdate();
NB: The performance increase of these two methods are almost double than Add() method.