带有列到listview winforms的导入列表C#

时间:2017-07-27 18:06:04

标签: c# winforms listview

您好我最近选择了C#并且已经完成了几个教程,但我仍然有很多需要学习的东西,所以如果我错误地设置了这个或者不是这个有效的方法,请提前道歉。

因此,正如标题所述,我正在尝试将列表导入列表视图。更具体地说,是一个将字符串放入listview的类。 (我仍然是这一切的新手,所以让我知道是否有更好的方法来解决这个问题。) 我想我知道如何根据这篇文章C# listView, how do I add items to columns 2, 3 and 4 etc?手动将listview项添加到列中 我现在所拥有的是使用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;
    }
}

我在下面的这个简短的代码片段中非常接近,但我需要能够添加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");(第1项),我也会感激不尽。)

我可以获得有关如何将类/列表直接添加到列表视图的建议吗?或者我应该如何重组我的课程,如果这是一个更好的解决方案。任何一般的命名惯例注释以及其他有用链接的链接也将受到赞赏 感谢。

1 个答案:

答案 0 :(得分:0)

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

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
    })));