【问题标题】:How to get a Listbox to read to a Listbox如何让列表框读取到列表框
【发布时间】:2014-05-29 18:38:31
【问题描述】:

我正在尝试打开任何选定的文本文件并将文本输入发送到列表框...最初我为一个文本框编写了这段代码,现在我将它转换为一个列表框它似乎不起作用所以效果很好很多。为了更好地理解发生了什么,我保留了默认项目名称。

private void button1_Click(object sender, EventArgs e)
{
   if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
   {
      label1.Text = openFileDialog1.FileName;
      listBox1.Items.Add = File.ReadAllText(label1.Text);
   }
}

【问题讨论】:

    标签: c# listbox openfiledialog


    【解决方案1】:
    listBox1.Items.AddRange(File.ReadAllLines(label1.Text));
    

    【讨论】:

      【解决方案2】:

      试试这个:

       listBox1.Items.AddRange(File.ReadLines(label1.Text).ToArray());
      

      【讨论】:

      • 不会编译的
      • .AddRange() 不会像你写的那样编译。它需要object[] itemsListBox.ObjectCollection value
      • 切换到这个实际上给了我两个单独的错误,由于某种原因它不喜欢这种方法
      • 抱歉,我修改了我的代码以适应AddRange(object[])
      【解决方案3】:

      .Add() 是一种方法,您将其视为属性。

      试试这个代码:

      listBox1.Items.Add(File.ReadAllText(label1.text));
      

      【讨论】:

      • 这不会将字符串分成几行。
      【解决方案4】:
      string[] lines = File.ReadLines("SomeFile.txt").ToArray();
      foreach (var line in lines)
      {
          listBox1.Items.Add(line);
      }
      

      【讨论】:

        【解决方案5】:
         private void button1_Click(object sender, EventArgs e)
                {
                    if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        label1.Text = openFileDialog1.FileName;
                        //till here the same
                        //open filestream
                        System.IO.StreamReader file = new System.IO.StreamReader(openFileDialog1.FileName);
                        //loop trough lines
                        while ((line = file.ReadLine()) != null)
                        {
                            //add line to listbox
                            listBox1.Items.Add ( line);
                        }
                    }
                }
        

        【讨论】:

        • 这告诉我“当前上下文中不存在名称行”
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-11
        • 2013-07-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多