0

When using

lvi.SubItems.AddRange(new ListViewItem.ListViewSubItem[5]);
Debug.Assert(lvi.SubItems.Count == 5);

the assert fails, lvi.SubItems.Count is 1, and accessing lvi.SubItems[1] fails.

What? Shouldn't that add 5 items?

(To clarify: I know I can add them individually using Add() - I'm asking why this doesn't work)


Larger context: listView1 is a winforms listview in Details view with 6 columns added:

   public Form1()
    {
        InitializeComponent();
        ListViewItem lvi = new ListViewItem();
        listView1.Items.Add(lvi);

        int expectedCount = 6;
        Debug.Assert(listView1.Columns.Count == expectedCount);
        if (lvi.SubItems.Count != expectedCount - 1)
        {
            lvi.SubItems.Clear();
            lvi.SubItems.AddRange(new ListViewItem.ListViewSubItem[expectedCount - 1]);
            Debug.Assert(lvi.SubItems.Count == expectedCount - 1);
        }

    }

(VS Express 2013RC, VS 2008 Pro)

4

1 回答 1

2

试试下面

lvi.BeginUpdate();
for (int i = 0; i < 5; i++)
   lvi.SubItems.Add(String.Empty); // adding empty items 
lvi.EndUpdate();
Debug.Assert(lvi.SubItems.Count == expectedCount - 1);

如果你想使用 AddRange

vi.SubItems.AddRange(Enumerable.Repeat(string.Empty, expectedCount - 1).ToArray());
于 2013-09-14T08:29:40.407 回答