Easily add column headers and items to a ListView control in C#

To add a row to a ListView control, you first add a new item and then add sub-items to the item. The ListViewMakeRow method shown in the following code makes this easier.

// Make a ListView row.
private void ListViewMakeRow(ListView lvw, String item_title, string[] subitem_titles)
{
// Make the item.
ListViewItem new_item = lvw.Items.Add(item_title);

// Make the sub-items.
for (int i = subitem_titles.GetLowerBound(0); i <= subitem_titles.GetUpperBound(0); i++)
{
new_item.SubItems.Add(subitem_titles[i]);
}
}

Now you can use this method as in:

ListViewMakeRow(lvwBooks, "Bug Proofing Visual Basic",
new string[] {
"http://www.vb-helper.com/err.htm",
"0-471-32351-9",
"http://www.vb-helper.com/err.jpg",
"397", "1999", "5/5/1999"
});

To give a ListView control column headers, you simply add new items to its Columns collection. The ListViewMakeColumnHeaders method makes it easy to add many headers all at once, specifying their titles and alignments.

// Make the ListView's column headers.
// The ParamArray entries should alternate between
// strings and HorizontalAlignment values.
private void ListViewMakeColumnHeaders(ListView lvw, Object[] header_info)
{
// Remove any existing headers.
lvw.Columns.Clear();

// Make the column headers.
for (int i = header_info.GetLowerBound(0); i <= header_info.GetUpperBound(0); i += 2)
{
lvw.Columns.Add(
(string)header_info[i],
-1,
(HorizontalAlignment)header_info[i + 1]);
}
}

The following code shows how you can call this method:

ListViewMakeColumnHeaders(lvwBooks,
new object[] {
"Title", HorizontalAlignment.Left,
"URL", HorizontalAlignment.Left,
"ISBN", HorizontalAlignment.Left,
"Picture", HorizontalAlignment.Left,
"Pages", HorizontalAlignment.Right,
"Year", HorizontalAlignment.Right,
"Pub Date", HorizontalAlignment.Right
});

This example uses these methods to easily load a ListView at run time.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.