Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add Column header to a ListView in C#

i'm having a ListView control with no columns.

an a list

List<String> MyList=new List<string>();

i need to create columns for each list MyList item in the ListView along with one another column for Serial Number.

For example if MyList contains "A", "B" ,"C"

then the list view will be like

alt text

I know that we can do this using for or foreach loop like

listView1.Columns.Add("S.No")
for(int i=0;i<MyList.Count;i++)
   {
      listView1.Columns.Add(MyList[i])
   }

but is there any way to do this using LINQ or LAMBDA Expression?

like image 701
Thorin Oakenshield Avatar asked Nov 02 '10 12:11

Thorin Oakenshield


2 Answers

MyList.ForEach(name => listView1.Columns.Add(name));
like image 135
Aliostad Avatar answered Oct 22 '22 03:10

Aliostad


Here are 4 options
there are at least another 10 ways to do this,

var myList = new List<string>() { "A", "B", "C" };

// 1: Modify original list and use List<>.ForEach()
myList.Insert(0, "S. No");
myList.ForEach(x => lisView.Columns.Add(x));

// 2: Add first column and use List<>.ForEach()
listView.Columns.Add("S. No");
myList.ForEach(x => listView.Columns.Add(x));

// 3: Don't modify original list
(new[] { "S. No" }).Concat(myList).ToList()
    .ForEach(x => listView.Columns.Add(x));

// 4: Create ColumnHeader[] with Linq and use ListView.Columns.AddRange()
var columns = (new[] { "S. No"}).Concat(myList)
    .Select(x => new ColumnHeader { Text = x }).ToArray();
listView.Columns.AddRange(columns);

Have you considered the KISS option?

like image 35
Yona Avatar answered Oct 22 '22 03:10

Yona