Yuri Makassiouk
Yuri Makassiouk

Reputation: 557

C# setting ListView's Item's Subitem's text does not display

I am losing my mind a little bit here. When I initially build up a ListView, it works totally as expected:

ListViewItem listViewItem = listView.Items.Add(model.Id.ToString(), model.Name, model.Id.ToString());
listViewItem.SubItems.AddRange(new ListViewItem.ListViewSubItem[]
  {
    new ListViewItem.ListViewSubItem() {Name = "ArtNr", Text = model.ArticleNumber},
    new ListViewItem.ListViewSubItem() {Name = "Quantity", Text = "XXX"},
  });

I have 3 columns defined in the control, and they display, respecively, Name, ArticleNumber and "XXX", to begin with.

At a later stage, I have to replace "XXX" with actual data, and do the following:

foreach (ListViewItem listViewItem in listView.Items)
  {
    InvoiceLine invoiceLine = FindInvoiceLine(...);
    if (invoiceLine == null)
        continue;

    listViewItem.SubItems["Quantity"].Text = invoiceLine.Quantity.ToString();
  }

I can see the Text actually being set in the proper SubItem.Text, also if I check later, while referencing the listview through a different reference, i.e. I know I am looking at the right object. However GUI does not reflect the change, it still says "XXX" in the 3rd column.

What gives?!

Upvotes: 2

Views: 1377

Answers (1)

KevinBui
KevinBui

Reputation: 1099

After digging source code .NET Framework, I found that it's definitively bug of AddRange method. They forgot to set owner of ListViewSubItem, so the text was not update when setting Text property.

You should use Add(ListViewSubItem) instead.

or use subitem constructor with parameter to set owner for it.

listViewItem.SubItems.AddRange(new ListViewItem.ListViewSubItem[]
  {
    new ListViewItem.ListViewSubItem(listViewItem, model.ArticleNumber) {Name = "ArtNr" },
    new ListViewItem.ListViewSubItem(listViewItem, "XXX") {Name = "Quantity" },
  });

Upvotes: 6

Related Questions