2017-07-27 39 views
0

嗨,我最近拿起C#和经历了几个教程,但我肯定还有很多东西要学习,尤其是在做,所以提前道歉,如果我已经设置了错误或上午不会采取这种有效的方式。列导入列表到列表视图winforms 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; 
    } 
} 

我已经非常接近以下这段简短的代码片段,但我需要能够添加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)我会很感激。)

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

回答

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

太棒了!谢谢你的帮助。因为我显然不够好地理解它们,所以有时间再回头看看构造函数。 –