3

我试图从 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);
        }
    }

编辑::: 添加了这个带有描述的截图...... 在此处输入图像描述

4

3 回答 3

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);
    }
}
于 2013-09-15T09:02:29.510 回答
0

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

于 2013-09-15T09:04:28.083 回答
-4

您的问题是“winforms 中的列表视图”。

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

listLeft.View = View.Details;

当我尝试重现时无法编译。

您是否可能指的是 WPF 列表框?在这种情况下,您能否向我们展示更多代码,尤其是您的数据绑定?

于 2013-09-15T09:04:23.427 回答