winforms中的C#listview不显示添加的项目

时间:2013-09-15 08:52:11

标签: c# winforms listview

我正在尝试从C#中的打开文件对话框中选择目录,但是当我实际将项目添加到列表视图时,它没有显示。到目前为止,这是我的代码......我错过了什么?

private void btnChoose_Click(object sender, EventArgs e)
    {
        try
        {
            FolderBrowserDialog folderPicker = new FolderBrowserDialog();
            listLeft.View = View.Details;
            if (folderPicker.ShowDialog() == DialogResult.OK)
            {
                DirectoryInfo di = new DirectoryInfo(folderPicker.SelectedPath);
                FileInfo[] files = di.GetFiles();
                DirectoryInfo[] directories = di.GetDirectories();

                foreach (DirectoryInfo directory in directories)
                {
                    listLeft.Items.Add("Directory " + directory.Name);
                }
                foreach (FileInfo file in files)
                {
                    listLeft.Items.Add(file.Name);
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("An error occurred: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

EDIT ::: 添加此屏幕截图及说明... enter image description here

3 个答案:

答案 0 :(得分:4)

我假设listLeft是你的ListView。你需要添加这样的子项:

            foreach (DirectoryInfo directory in directories)
            {
                ListViewItem lvi = new ListViewItem();
                lvi.SubItems.Add("Directory " + directory.Name);
                listLeft.Items.Add(lvi);
            }
            foreach (FileInfo file in files)
            {
                ListViewItem lvi = new ListViewItem();
                lvi.SubItems.Add(file.Name);
                listLeft.Items.Add(lvi);
            }

编辑:试试这个:

private void button1_Click(object sender, EventArgs e)
{
    try
    {
        listLeft.Columns.Add(new ColumnHeader());
        FolderBrowserDialog folderPicker = new FolderBrowserDialog();
        listLeft.View = View.Details;
        if (folderPicker.ShowDialog() == DialogResult.OK)
        {
            DirectoryInfo di = new DirectoryInfo(folderPicker.SelectedPath);
            FileInfo[] files = di.GetFiles();
            DirectoryInfo[] directories = di.GetDirectories();

            foreach (DirectoryInfo directory in directories)
            {
                listLeft.Items.Add("Directory " + directory.Name);
            }
            foreach (FileInfo file in files)
            {
                listLeft.Items.Add(file.Name);
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("An error occurred: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

答案 1 :(得分:0)

它应该添加到列表框中 - 如果目录和文件对象中有对象...尝试在每个方法中设置断点并查看发生的情况。如果没有触发断点,则Get()方法出现问题......

答案 2 :(得分:-4)

你的问题陈述了'winforms'中的列表视图。

但是System.Windows.Forms.ListBox没有View属性,所以你的代码行

listLeft.View = View.Details;
当我尝试重现时,

无法编译。

您是指代WPF列表框吗? 在这种情况下,您能告诉我们更多代码,特别是您的数据绑定吗?