【问题标题】:import list with columns to listview winforms C#将带有列的列表导入listview winforms C#
【发布时间】:2017-07-27 18:06:03
【问题描述】:

您好,我最近学习了 C# 并学习了一些教程,但我肯定还有很多东西要学习,尤其是在实践中,所以如果我设置不正确或没有以有效的方式进行此操作,请提前道歉。

正如标题所述,我正在尝试将带有列的列表导入列表视图。更具体地说,一个带有字符串的类到一个列表视图中。 (我对这一切还是陌生的,所以让我知道是否有更好的方法来解决这个问题。) 我想我知道如何根据这篇文章C# listView, how do I add items to columns 2, 3 and 4 etc? 手动将列​​表视图项添加到列中 我现在使用的是lstViewPrinters.Items.Add(_printerlist[i].ToString());,但这会将整个类“打印机”作为单个列表视图项添加到单个列中。我知道我也可以通过_printerlist[i].Hostname.ToString(); 访问单个字符串。 我的班级的相关布局如下所示。

List<Printer> _printerlist = new List<Printer>();
public class Printer
{
    public string Hostname { get; set; }
    public string Manufacturer { get; set; }
    public string Model { get; set; }


    public Printer() // this is a method within the Printer class
    {
        Hostname = string.Empty;
        Manufacturer = string.Empty;
        Model = string.Empty;
    }
}

我已经非常接近下面这个短代码 sn-p,但我需要能够添加 2 个项目。

for(int i=0; i<_printerlist.Count; i++)
{lstViewPrinters.Items.Add(_printerlist[i].Hostname).SubItems.Add(_printerlist[i].Manufacturer);}

最好的方法是让它成为一个范围并删除加倍的列吗?我看到的另一种方法是使用item1.SubItems.Add("SubItem1a"); 命令添加项目,但我的系统在for 循环中,所以我不能这样做(或者至少我不知道如何,如果有人可以指导我声明ListViewItem item1 = new ListViewItem("Something"); 在循环中更改名称(item1)我也将不胜感激。)

我能否获得有关如何将类/列表直接添加到列表视图的建议?或者我应该如何重组我的班级,如果这是一个更好的解决方案。任何通用命名约定说明以及指向其他有用链接的链接也将不胜感激。
谢谢。

【问题讨论】:

    标签: c# winforms listview


    【解决方案1】:

    ListViewItem有一堆构造函数,你可以像这样在new语句中添加所有属性

    var _printerlist = new List<Printer>();
    
    for (int i = 0; i < _printerlist.Count; i++)
    {
        lstViewPrinters.Items.Add(
            new ListViewItem(new[]
            {
                _printerlist[i].Hostname,
                _printerlist[i].Manufacturer,
                _printerlist[i].Model
            }));
    }
    

    或者为了好玩,您可以使用 LINQ 在一个语句中完成整个事情

    _printerlist.ForEach(p => lstViewPrinters.Items.Add(
        new ListViewItem(new[]
        {
            p.Hostname,
            p.Manufacturer,
            p.Model
        })));
    

    【讨论】:

    • 太棒了!谢谢你的帮助。是时候回去再看看构造函数了,因为我显然对它们理解得不够好。
    猜你喜欢
    • 1970-01-01
    • 2011-12-16
    • 2016-02-28
    • 1970-01-01
    • 2018-10-18
    • 1970-01-01
    • 2011-02-17
    • 2019-11-28
    • 2010-12-13
    相关资源
    最近更新 更多