从记事本中获取数据的组合框

时间:2013-05-23 20:20:40

标签: c# combobox

我有组合框,我需要在表单加载时从记事本中获取数据。我的代码是

    private string[] items;

    private void Form1_Load(object sender, EventArgs e)
    {
        if (cmbItems.SelectedIndex == -1)
        {
            items= File.ReadAllLines(@"C:\Users\atchyutkumar\Downloads\data.txt");
        }

2 个答案:

答案 0 :(得分:2)

如果您的意图是从文本文件中读取所有行并将它们放入组合框

cmbItems.Items.AddRange(File.ReadAllLines(filename));

答案 1 :(得分:0)

private void Form1_Load(object sender, EventArgs e)
{
   StreamReader sr = new Streamreader(YourTxtFilePath);
   string str = null;
   while( (str = sr.ReadLine()) != null)
   {
     if (cmbItems.SelectedIndex == -1) // If the comboBox is empty
     {
       cmbItems.Items.Add(str);     // Add the strings in the .txt file
     }
   }
}

我不确定这是你想要的还是我的代码可能是错的。所以,随时纠正我。 ;)