在 C# 中轻松向 ListView 控件添加列标题和项目

通常,要向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 。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

坐井观老天

您的鼓励是我分享的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值