通常,要向ListView 控件添加一行,首先要添加一个新项,然后向该项添加子项。以下代码显示了ListView类的AddRow扩展方法,该方法使添加新行更加容易。
// Add the items as a new row in the ListView control.
public static void AddRow(this ListView lvw, string[] items)
{
// Make the main item.
ListViewItem new_item = lvw.Items.Add(items[0]);
// Make the sub-items.
for (int i = 1; i < items.Length; i++)
new_item.SubItems.Add(items[i]);
}
此代码采用要添加到行中的字符串参数数组。它使用第一个值来创建新项目。然后,它将其他值添加为子项目。
如果lvwBooks是一个ListView控件,则可以按如下方式使用此方法:
lvwBooks.AddRow(new string[] {
"C# 5.0 Programmer's Reference",
"http://tinyurl.com/qzcefsp",
"978-1-118-84728-2", "960", "2014" });
由于项目列表是一个参数数组,因此您还可以使用扩展方法,如下所示:
lvwBooks.AddRow(
"Beginning Database Design Solutions",
"http://www.vb-helper.com/db_design.htm",
"978-0-470-38549-4", "552", "2008");
要将列标题添加到ListView控件,通常需要将新项目添加到其Columns集合中。以下 MakeColumnHeaders扩展方法可让您轻松地一次性添加所有标题,并指定其标题和对齐方式。
// Make the ListView's column headers.
// The ParamArray entries should alternate between
// strings and HorizontalAlignment values.
public static void MakeColumnHeaders(this ListView lvw,
params object[] header_info)
{
if (header_info.Length % 2 != 0)
throw new ArgumentException(
"The method must have an even number " +
"of header_info parameters");
// Remove any existing headers.
lvw.Columns.Clear();
// Make the column headers.
for (int i = 0; i < header_info.Length; i += 2)
{
lvw.Columns.Add(
(string)header_info[i],
-1,
(HorizontalAlignment)header_info[i + 1]);
}
}
该方法首先验证header_info参数数组是否包含偶数个项目。然后清除ListView控件的Columns集合。最后,添加标头值,指定列宽为 -1(适合数据的大小)和通过参数数组传入的水平对齐方式。
主程序使用下面的代码来调用该扩展方法。
// Make the ListView column headers.
lvwBooks.MakeColumnHeaders(
"Title", HorizontalAlignment.Left,
"URL", HorizontalAlignment.Left,
"ISBN", HorizontalAlignment.Left,
"Pages", HorizontalAlignment.Right,
"Year", HorizontalAlignment.Right
);
该程序对其ListView控件执行了另外两件有趣的事情。首先,它使用以下扩展方法一次性设置控件的所有列大小。
// Set all columns' sizes.
public static void SizeColumns(this ListView lvw, int size)
{
for (int i = 0; i < lvw.Columns.Count; i++)
lvw.Columns[i].Width = -2;
}
主程序使用下面的语句调用该方法。
lvwBooks.SizeColumns(-2);
最后,主程序使用下面的代码来调整窗体的大小以适合ListView控件。
// Make the form big enough to show the ListView.
Rectangle item_rect =
lvwBooks.GetItemRect(lvwBooks.Items.Count - 1);
this.ClientSize = new Size(
item_rect.Left + item_rect.Width + 25,
item_rect.Top + item_rect.Height + 25);
代码使用ListView控件的GetItemRect方法获取控件中最后一项的边界矩形。然后,它使用该矩形的尺寸使窗体足够大,以便一次显示整个ListView 。