Resolved How to transfer a specific listview column items to a listbox in C#

Joined
Jul 7, 2022
Messages
7
Programming Experience
10+
Hello everyone. I will be grateful for your kind help on this one. I am trying to transfer a specific listview column items to a listbox in C#. Heres my effort below.
Unfortunately my code rather iterates though only the entry of the specified column and splits it as letters into the listbox. For a example if the entry there is "HELLO"
It rather transfer it to the list box as:
H
E
L
L
O

And not rather the next in the row of that column.


C#:
            private void Button1_Click(object sender, EventArgs e)
        {
            foreach (var item in Listview.Items[5].Text)
            {
                this.lstTask.Items.Add(item);
            }
        }
 
That's because Listview.Items[5].Text is a string. If you use that as a subject of a foreach, a string will return the individual characters.
 
To access each row, you need to change the index that you are using on the Items collection. To access specific columns of a row, you need to access the SubItems of each row.
 
The simplest option here is a LINQ query:
C#:
var values = myListView.Items
                       .Cast<ListViewItem>()
                       .Select(lvi => lvi.SubItems[5].Text)
                       .ToArray();
That will give you a string array containing the text from the sixth column. You can then call AddRange to add all items to the ListBox in one go or assign the array to the DataSource property.
 
The simplest option here is a LINQ query:
C#:
var values = myListView.Items
                       .Cast<ListViewItem>()
                       .Select(lvi => lvi.SubItems[5].Text)
                       .ToArray();
That will give you a string array containing the text from the sixth column. You can then call AddRange to add all items to the ListBox in one go or assign the array to the DataSource property.
Thank you. This was very helpful. All I did was just still using the foreach loop to add the values to the listbox. LIke below, and it worked perfectly.


C#:
        this.lstTask.Items.Clear();
            var values = this.lstvAppExecute.Items
                                   .Cast<ListViewItem>()
                                   .Select(lvi => lvi.SubItems[8].Text)
                                   .ToArray();       

            foreach (var item in values)
            {
                this.lstTask.Items.Add(item);
            }



~ thanks guys
 
Back
Top Bottom