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)

1 Answer 1

2

try below

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); 

if you want to use AddRange

vi.SubItems.AddRange(Enumerable.Repeat(string.Empty, expectedCount - 1).ToArray()); 
Sign up to request clarification or add additional context in comments.

3 Comments

Yeah, I have a worekaround, I am wondering why AddRange doesn't work (or whether I'm doing something wrong with it)
when you add ListViewSubItem[expectedCount - 1] all sub items are null, that may be the reason behind this
d'oh, I was thinking structs, not objects. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.