C
C#2y ago
Cake

❔ How to add rows in ListView using For loop?

So I'm trying to add multiple rows in ListView using loops. I write up this
C#
for(int i = 0; i < AList.Count; i++)
{
int n = i + 1;
string [] row = {n.ToString(), AList[i].ToString() + "×" + BList[i].ToString() + "=", PAList[i].ToString(), CAList[i].ToString() };
var listViewItem = new ListViewItem(row);
ResultListView.Items.Add(listViewItem);

}
C#
for(int i = 0; i < AList.Count; i++)
{
int n = i + 1;
string [] row = {n.ToString(), AList[i].ToString() + "×" + BList[i].ToString() + "=", PAList[i].ToString(), CAList[i].ToString() };
var listViewItem = new ListViewItem(row);
ResultListView.Items.Add(listViewItem);

}
And I only get 1 row filled seem in the screenshot I took. When I put in string [i] row = , I get the error CS0270 Array size cannot be specified in a variable declaration (try initializing with a 'new' expression).
5 Replies
HtmlCompiler
HtmlCompiler2y ago
you have to use Items.AddRange to add more than one item a single call like
ResultListView.Items.AddRange(new []
{
new ListViewItem(new[] { "stuff" }),
new ListViewItem(new[] { "moar" })
})
ResultListView.Items.AddRange(new []
{
new ListViewItem(new[] { "stuff" }),
new ListViewItem(new[] { "moar" })
})
Cake
CakeOP2y ago
But how would I add the range based on the number of items in the list (for AList)?
HtmlCompiler
HtmlCompiler2y ago
i don't understand the question
Johnny Rage
Johnny Rage2y ago
It's WinForms or WPF? WPF > ObservableCollection<Model> and it would be added automatically...
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.

Did you find this page helpful?