2014-07-23 21 views
1

请原谅我这样一个愚蠢的问题。我相信你们中的很多人会发现这种简单的方式,在那里我几乎每天都有半天的时间想要弄明白这一点。C#ListView来自另一个函数

这里的问题是:

  1. 我做了一个表格(Form1.cs中)。在这种形式下,我创建了一个listview,并将其命名为“ListView1”。
  2. 在Form1.cs中,我调用一个名为FileManager(this)的函数,在这里我传入THIS对象。
  3. 在FileManager.cs中,我能够listviewArray = originalForm.Controls.Find(“listView1”,true)并找到'listview'。
  4. 当我做一个listviewArray [0] < - 我似乎无法添加一个列表。

FileManager.cs

FileManager(object sender) 
    { 
     if (sender != null) 
     { 
      originalForm = (Form)sender; 
     } 


    } 
    public void getFiles() 
    { 
     filePaths = Directory.GetFiles(hsocDir); 
     if(filePaths != null) 
     { 
      listviewArray= originalForm.Controls.Find("listView1", true); 
      if(listviewArray != null) 
      { 
       ListViewItem lvi = new ListViewItem("text"); 

       // My Array is listViewArray 
       // How to add things to Lvi to it. 

      } 
     } 


== Form1.cs 
public Form1() 
     { 
      InitializeComponent(`enter code here`); 
      mysql = new MySQLCheck(this); 
      fileManager = new FileManager(this); 
      fileManager.getFiles(); 
     } 

回答

0

因为集合是空的,你不能访问集合的元素0。要添加一个项目,使用方法:

listViewArray.Items.Add(lvi); 

您需要修改Items集合,而不是在ListView本身对于这项工作,因为ListView不是一个集合(其控制)。

在您的列表视图
+0

问题1:我用找到ListView1的方法对象把东西添加到它时,正确的路线? – FlyingV

+0

@ user3443386这是一个非常合理的方法。更好的办法是抛弃直接的UI操作并使用MVVM实现(可能与WPF一起)。话虽如此,你可能还没有准备好重写你的项目,所以它看起来没问题。 – BradleyDotNET

0
listViewArray.Items.Add(lvi); 

而且,设置该属性将帮助:

 // Set the view to show details. 
     listViewArray.View = View.Details; 
     // Select the item and subitems when selection is made. 
     listViewArray.FullRowSelect = true; 
     // Display grid lines. 
     listViewArray.GridLines = true; 
相关问题