Inserting elements in a ListView
In this section, you can see how to change the getAdd() stub with code that let you insert a bulk of elements into a ListView.
Description
Certain code patterns in VB6 to insert a massive amount of elements in a ListView may present a performance gap in .NET when the code is converted. This entry covers that situation and how it can be fixed manually.
Inserting elements
In VB6 it is common to find a loop, like a do-while, iterating over a list of elements and inserting them into a ListView. Let's consider the following example:
Private Sub Form_Load()
Dim ss(6) As String
ss(1) = "this"
ss(2) = "is"
ss(3) = "a"
ss(4) = "sample"
ss(5) = "of"
ss(6) = "code"
Dim lv As ListItem
k = 1
Do While k < 7
Set lv = Me.ListView1.ListItems.Add
lv.Text = ss(k)
k = k + 1
Loop
End Sub
When converted, that code will look like:
private void Form_Load()
{
string[] ss = new string[]{"", "", "", "", "", "", ""};
ss[1] = "this";
ss[2] = "is";
ss[3] = "a";
ss[4] = "sample";
ss[5] = "of";
ss[6] = "code";
ListViewItem lv = null;
int k = 1;
while(k < 7)
{
//UPGRADE_ISSUE: (2064) MSComctlLib.IListItems method ListView1.ListItems.Add was not upgraded.
lv = this.ListView1.Items.getAdd();
lv.Text = ss[k];
k++;
};
}
Besides the manual change to overcome the getAdd() stub, that can be replaced by something like:
lv = new ListViewItem();
listView1.Items.Add(lv);
However, inserting one ListViewItem at a time can take a lot of time in .NET. Instead of this way of adding elements, consider inserting a bulk of elements at once:
private void Form_Load()
{
string[] ss = new string[]{"", "", "", "", "", "", ""};
ss[1] = "this";
ss[2] = "is";
ss[3] = "a";
ss[4] = "sample";
ss[5] = "of";
ss[6] = "code";
List<ListViewItem> items = new List<ListViewItem>();
ListViewItem lv = new ListViewItem();
int k = 1;
while(k < 7)
{
lv = new ListViewItem();
items.Add(lv);
lv.Text = ss[k];
k++;
};
listView1.Items.AddRange(items.ToArray());
}
The above while-loop insert elements into a typed List of ListViewItem and then, after the while, the ListView.AddRange() method is used to insert the bulk of items.
Last updated
Was this helpful?