使用目录文件填充ComboBox

时间:2016-02-22 20:43:43

标签: c#

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace POC1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

            string[] files = Directory.GetFiles(@"C:\\");
            foreach (string file in files)
            {
                comboBox1.Items.AddRange(files);
            }
        }

    }
}

我使用以下代码,但我无法使用我的组合框来填充任何数据。我很确定我使用了我搜索过的例子。

2 个答案:

答案 0 :(得分:1)

并不是说它可能会有所不同,但你的循环并添加所有目录的目录数量。应该更像是

string[] files = Directory.GetFiles(@"C:\\");
        foreach (string file in files)
        {
            comboBox1.Items.Add(file);
        }

或更简单

comboBox1.Items.AddRange(Directory.GetFiles(@"C:\\"));

除非你把它放在其他地方(自从我使用winforms以来已经有一段时间),你需要设置表单加载事件。

this.Load += Form1_Load;

答案 1 :(得分:0)

您需要删除循环并拥有单个.AddRange(文件),或者将循环内的行更改为comboBox.Items.Add(文件),因为上面的示例是为每次迭代添加所有文件。 / p>

值得注意的是,在添加项目时,它不必是一个字符串,但可以是一个对象,它只需要适当地响应.ToString()。

请参阅此链接https://social.msdn.microsoft.com/Forums/windows/en-US/c7a82a6a-763e-424b-84e0-496caa9cfb4d/how-add-a-item-to-combobox?forum=winforms