adding items to listview in loop
I have a problem with listview. I am not sure how to use a loop to fill the items. The following code works for the first row and I think that I need to increment the row but I'm not sure how. When the list contains more than 1 entry I get the error message:
Failed to compare two elements in the array
foreach (List<string> l in list)
{
ListViewItem item = new ListViewItem(l[0]);
item.SubItems.Add(l[1]);
item.SubItems.Add(l[2]);
item.SubItems.Add(l[3]);
item.SubItems.Add(l[4]);
lstBooks.Items.Add(item);
}
below is the whole function. I originally had a problem with the list but it was solved here populating a list of a list of strings but
The view is set to details
private void ListBo开发者_如何转开发oks()
{
lstBooks.Items.Clear();
lstBooks.Columns.Clear();
lstBooks.Visible = true;
List<List<string>> list = db.ListDetailsByGenre();
lstBooks.Columns.Add("Title", 120);
lstBooks.Columns.Add("Author", 120);
lstBooks.Columns.Add("Library", 120);
lstBooks.Columns.Add("Genre", 120);
foreach (List<string> l in list)
ListViewItem item = new ListViewItem(l[0]);
item.SubItems.Add(l[1]);
item.SubItems.Add(l[2]);
item.SubItems.Add(l[3]);
item.SubItems.Add(l[4]);
lstBooks.Items.Add(item);
}
}
foreach (List<string> l in list)
ListViewItem item = new ListViewItem(l[0]);
item.SubItems.Add(l[1]);
item.SubItems.Add(l[2]);
item.SubItems.Add(l[3]);
item.SubItems.Add(l[4]);
lstBooks.Items.Add(item);
}
You are missing an { after your foreach (List l in list) when you uploaded the larger portion of the code but not when you showed the function itself.
I created the following test and no errors occurred.
List<List<string>> list = new List<List<string>>();
list.Add(new List<string> { "1a", "1b", "1c", "1d", "1e" });
list.Add(new List<string> { "2a", "2b", "2c", "2d", "2e" });
list.Add(new List<string> { "3a", "3b", "3c", "3d", "3e" });
list.Add(new List<string> { "4a", "4b", "4c", "4d", "4e" });
list.Add(new List<string> { "5a", "5b", "5c", "5d", "5e" });
foreach (List<string> l in list)
{
ListViewItem item = new ListViewItem(l[0]);
item.SubItems.Add(l[1]);
item.SubItems.Add(l[2]);
item.SubItems.Add(l[3]);
item.SubItems.Add(l[4]);
lstBooks.Items.Add(item);
}
Some points:
The problem may be in the structure/data of
list
- provide an example of the contents oflist
.The
Add
method simply adds the ListViewItem to the end of the Items collection of the ListView, so you don't need to increment the row.It likely doesn't apply here, but you might want or need to clear the existing items from the ListView before populating it:
lstBooks.Items.Clear();
What other listview properties might be changed from default, and at what point do you get the error?
精彩评论