【问题标题】:C# WinForms ListView not displaying items/files/foldersC# WinForms ListView 不显示项目/文件/文件夹
【发布时间】:2019-11-24 09:37:32
【问题描述】:

我想在列表视图中显示文件名,但问题是列表视图没有显示任何项目。 奇怪的是 listview.items.count 表明项目已正确添加。 项目只是没有显示在任何类型的 listview.view 中。 编辑:ListView 被拖放到选项卡控件上。


string[] files;
bool error = false;

    try   
    {        
          files = Directory.GetFiles(addDir /* this is the folder path*/, "*.txt", SearchOption.AllDirectories);

    }
    catch(Exception ex)
    {
        // the code will jump here if there any access restrictions
        MessageBox.Show(ex.Message);

        error = true;
    }

    if(!error)
    {
        foreach (string fi in files)
        {
            string fnameonly = System.IO.Path.GetFileNameWithoutExtension(fi);
            _listView1.Items.Add(fnameonly);
        }
    }

【问题讨论】:

  • 这段代码在哪里?它与 listVIew1 变量的形式相同吗?您如何获得对该变量 listView1 的引用?
  • @Steve 是的,代码与变量 listView1 的形式相同。
  • 抱歉,没有足够的上下文来理解这里发生了什么。使用调试器检查文件数组是否填充了数据。还要确保对同一个表单实例进行操作,而不是创建一个新的表单实例。
  • 也许您在设计器/代码中设置了OwnerDraw = true?也许 ForeColor 与 BackColor 相同?
  • @Jimi 我检查了 OwnerDraw = false 和 BackColor 和 ForeColor 是不同的。当我单击 listView1 上的任意位置时,方法 => _listView1_SelectedIndexChanged(object sender, EventArgs e) 也没有调用。

标签: c# .net windows winforms listview


【解决方案1】:

这是一个非常愚蠢的错误,花了好几天才发现。我不小心为通过拖放操作创建的 ListView 控件分配了内存。

【讨论】:

    【解决方案2】:

    有时,创建一个新项目、验证它是否正常工作,然后添加更多功能,直到您了解是什么破坏了您的程序,这会有所帮助。下面的示例仅显示一个包含两个文件的 ListView。确保这适用于您的机器。然后慢慢添加更多代码,并始终检查您的程序是否仍然有效。我将所有代码放在一个文件中,因为它更容易在堆栈溢出时发布,但您可以将其拆分为单独的文件。

    另请参阅ListView documentation

    using System;
    using System.IO;
    using System.Windows.Forms;
    
    namespace WindowsFormsApp
    {
        public class ListViewDemo : Form
        {
            public ListViewDemo()
            {
                var _listView1 = new ListView();
    
                string[] files = { @"C:\tmp\file1.txt", @"c:\path\to\file2.doc" };
                foreach (string fi in files)
                {
                    string fnameonly = Path.GetFileNameWithoutExtension(fi);
                    _listView1.Items.Add(fnameonly);
                }
    
                AutoSize = true;
                Controls.Add(_listView1);    
            }
        }
    
        static class Program
        {    
            [STAThread]
            static void Main()
            {
                Application.Run(new ListViewDemo());
            }
        }
    }
    

    【讨论】:

    • 这确实有效。谢谢!我m actually creating a media player so Im 一一添加功能,但 listView 在主项目上不起​​作用。
    • 编辑:添加到选项卡控件时的列表视图不显示任何项目,否则它正在工作。
    猜你喜欢
    • 2011-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-23
    • 1970-01-01
    • 1970-01-01
    • 2022-07-16
    • 2015-11-03
    相关资源
    最近更新 更多