Search code examples
vb.netlistviewmultiple-columns

vb.net populate multicolumn listview


I'm a very newbie with VB.NET so excuse me for silly question. I have a two-dimensional array and want populate listview with it's elements. For this I'm trying use something like this:

lst_arrayShow.Items.Clear()
    For currentColumn As Integer = 0 To (columnsCnt - 1)
        lst_arrayShow.Columns.Add("")
        For currentRow As Integer = 0 To (rowsCnt - 1)
            'lst_arrayShow.Items.Add()
        Next
    Next

What should I use instead of 'lst_arrayShow.Items.Add() ?
UPD: columnsCnt is number of columns in array and rowsCnt is number of rows in array


Solution

  • In a multicolumn ListView you need to set the property View to View.Details and then be sure to define all the columns needed. So, if you haven't already done it in the Designer, you need to add the columns required to your ListView

    lst_arrayShow.View = View.Details
    For currentColumn As Integer = 0 To (columnsCnt - 1)
        lst_arrayShow.Columns.Add("Column Nr: " & currentColumn
    Next
    

    Next, now that you have defined the columns, you could loop over your rows and create a ListViewItem for each row.
    The ListViewItem has a Subitems collection that correspond to the Columns defined above

    For currentRow As Integer = 0 To (rowsCnt - 1)
    
        ' Create the ListViewItem with the value from the first column
        Dim item = new ListViewItem(yourArray(currentRow,0))
        
        ' The remainder columns after the first are added to the SubItems collection
        For currentColumn As Integer = 1 To (columnsCnt - 1)
             item.SubItems.Add(yourArray(currentRow,currentColumn))
        Next
        
        ' Finally, the whole ListViewItem is added to the ListView
        lst_arrayShow.Items.Add(item)
    Next