ElektroStudios
ElektroStudios

Reputation: 20464

Array of string to ListViewItemCollection

How I can add in one step an Array of string into a Listview for example using LINQ or Casting methods?

This is what I've tried but does not work:

ListView1.Items.AddRange("a b c d e f".Split(" ").ToArray _
.Select(Function(x) New ListViewItem(x)))

UPDATE:

Another try, does not work:

ListView1.Items.AddRange( _
    New ListView.ListViewItemCollection( _
    {"Value 1", "Value 2", "Value 3"} _
   .Select(Function(x) New ListViewItem(x))))

Upvotes: 3

Views: 2968

Answers (4)

matsolof
matsolof

Reputation: 265

It seems you have to set the first column with 'Items.Add' and the rest of the columns with 'SubItems.AddRange'. This is the code I use to accomplish that:

string[] arr = "column1|column2|column3".Split('|');
ListView1.Items.Add(arr[0]).SubItems.AddRange(new string[] { arr[1], arr[2] });

Upvotes: 2

pescolino
pescolino

Reputation: 3123

AddRange expects an array but the Select function returns an IEnumerable. So you just have to add ToArray to the end of the expression. Since Split returns a string array there is no need to add a call to ToArray there.

This will do the job:

ListView1.Items.AddRange("a b c d e f".Split(" "c) _
                                      .Select(Function(x) New ListViewItem(x)) _
                                      .ToArray)

Upvotes: 4

ElektroStudios
ElektroStudios

Reputation: 20464

Done!

I hope this helps someone else:

  ' Set the Array content
  Dim Items As String() = "ABC DEF GHI JKL".Split

  ' Add them in one step
  ListView1.Items.AddRange(Items.Select(Function(x) New ListViewItem(x)).ToArray)

Upvotes: 0

Jaycee
Jaycee

Reputation: 3118

ListView1.Items.AddRange("a b c d e f".Split(" ".ToCharArray()))

The above should be the correct syntax in order to add those characters as the list

EDIT Think I missed the ListViewItem collection out

ListView1.Items.AddRange(new ListViewItem("a b c d e f".Split(" ".ToCharArray())))

Upvotes: 1

Related Questions