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.Now you can use this method as in:
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]);
}
}
ListViewMakeRow(lvwBooks, "Bug Proofing Visual Basic",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.
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"
});
// Make the ListView's column headers.The following code shows how you can call this method:
// 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]);
}
}
ListViewMakeColumnHeaders(lvwBooks,This example uses these methods to easily load a ListView at run time.
new object[] {
"Title", HorizontalAlignment.Left,
"URL", HorizontalAlignment.Left,
"ISBN", HorizontalAlignment.Left,
"Picture", HorizontalAlignment.Left,
"Pages", HorizontalAlignment.Right,
"Year", HorizontalAlignment.Right,
"Pub Date", HorizontalAlignment.Right
});


Comments