Copy data in a two-dimensional array into a ListView control in C#


ListView control
The CopyArrayToListView method shown in the following code copies data from a two-dimensional array into a ListView control.

// Copy a two-dimensional array of data into a ListView.
private void CopyArrayToListView(ListView lvw, string[,] data)
{
    int max_row = data.GetUpperBound(0);
    int max_col = data.GetUpperBound(1);
    for (int row = 0; row <= max_row; row++)
    {
        ListViewItem new_item = lvw.Items.Add(data[row, 0]);
        for (int col = 1; col <= max_col; col++)
        {
            new_item.SubItems.Add(data[row, col]);
        }
    }
}

The code first uses the array’s GetUpperBound method to get the upper bounds of the first and second dimensions (rows and columns respectively).

Next the code loops through the rows. For each row, it adds a new item to the ListView. It then loops through the columns, adding the other items for that row as sub-items to the row.


Download Example   Follow me on Twitter   RSS feed


This entry was posted in controls and tagged , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *