Omar AlMadani
Omar AlMadani

Reputation: 201

Add items to a specific Column of a ListView in winforms

I am creating a WinForms application in visual studio 2017,

I am adding two columns to my ListView,

        ListView1.Columns.Add("Column1", -2, HorizontalAlignment.Left);
        ListView1.Columns.Add("Column2", -2, HorizontalAlignment.Left);

I am looping a List of strings, I would like to split it in half, where the first half goes to Column1 and the second goes to Column 2.

        List<String> strings;

I have looked at many soloutions online using subItems instead, I cannot use subItems because:

  1. I need all the items to be selectable
  2. Some of the strings vary in size, so I would like the columns to be flexible to be able to display the entire string
  3. I need all the strings to be aligned to the left side

A sample of what it should like

Column1                Column2           
STRING 1               STRING 100002
STRING 10000           STRING 2222
STRING 144             STRING XCEZ
STRING 144             STRING IK?
STRING 144             STRING 5

Does anyone know how to do this ? thank you in advance.

Upvotes: 2

Views: 2936

Answers (1)

Reza Aghaei
Reza Aghaei

Reputation: 125197

I'm not sure why you have a List<string> rather than having a List<MyClass>, which MyClass has two properties, Property1 and Property2.

Anyway, regarding to your question, you can use a for loop like this:

var list = new List<string> { "1", "2", "3", "4" };
var count = list.Count;
listView1.BeginUpdate();
for (var i = 0; i < count / 2; i++)
    listView1.Items.Add(list[i]).SubItems.Add(list[count / 2 + i]);
listView1.EndUpdate();

Upvotes: 1

Related Questions