【问题标题】:C# ListView from Another Function来自另一个函数的 C# ListView
【发布时间】:2014-07-23 08:27:21
【问题描述】:

请原谅我问了这么愚蠢的问题。我相信你们中的许多人会发现这很容易,我已经发送了近半天的阅读时间试图弄清楚这一点。

问题来了:

  1. 我制作了一个 FORM (Form1.cs)。在该表单中,我创建了一个列表视图,并将其命名为“ListView1”。
  2. 在 Form1.cs 中,我调用了一个名为 FileManager(this) 的函数,并在其中传入了 THIS 对象。
  3. 在 FileManager.cs 中,我能够 listviewArray= originalForm.Controls.Find("listView1", true) 并找到“listview”。
  4. 当我执行 listviewArray[0]

文件管理器.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();
        }

【问题讨论】:

    标签: c#


    【解决方案1】:

    您无法访问集合的元素 0,因为集合是空的。要添加项目,请使用:

    listViewArray.Items.Add(lvi);
    

    您需要修改Items 集合而不是ListView 本身,因为ListView 不是集合(它是一个控件)。

    【讨论】:

    • 问题 1:当我尝试向 listView1 对象添加内容时,我用来查找 listView1 对象的方法是否正确?
    • @user3443386 这是一个非常合理的方法。更好的办法是抛弃直接的 UI 操作并使用 MVVM 实现(可能使用 WPF)。话虽如此,您可能还没有准备好重新编写您的项目,所以看起来还不错。
    【解决方案2】:
    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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-28
      • 2017-03-27
      • 1970-01-01
      • 2012-02-16
      • 2017-03-08
      • 1970-01-01
      • 2020-08-11
      相关资源
      最近更新 更多