【问题标题】:Fill Listbox with values from TextFile用文本文件中的值填充列表框
【发布时间】:2013-11-01 08:04:36
【问题描述】:

我的代码有问题。我的代码必须从文本文件中读取值,它确实如此。但是当我将文本文件的值放在我的列表框中时,结果如下:

所以命令或值都在一行中。 我希望命令是这样的,我已经改变了图片,所以你可以看到:

所以你看到了吗?我想要彼此下的命令。这是我读取文本文件的代码:

private void CommandFileSelectButton_Click(object sender, EventArgs e)
    {
        Stream mystream;
        OpenFileDialog commandFileDialog = new OpenFileDialog();


        if (commandFileDialog.ShowDialog() == DialogResult.OK)
        {
            if ((mystream = commandFileDialog.OpenFile())!= null)
            {
                string fileName = commandFileDialog.FileName;
                CommandListTextBox.Text = fileName;
                string fileText = File.ReadAllText(fileName);
                _commandList.Add(fileText);
                CommandListListBox.DataSource = _commandList;
            }

        }
    }

_commandList 是我的同事制作的本地函数。

这是TextFile的样子:

RUN 
RUNW
STOP
RUN
RUN
STOP

提前感谢您的帮助。

【问题讨论】:

  • 您可以在每个文件文本后添加新行。
  • 你能再解释一下,让我明白你的意思吗?
  • 文件中的命令是在不同的行还是在同一行??
  • 命令在不同的行
  • 使用string[] File.ReadAllLines() 代替string File.ReadAllText() 并使用foreach 循环添加单独的行。

标签: c# file-io io listbox


【解决方案1】:
CommandListListBox.DataSource = File.ReadAllLines(fileName);

【讨论】:

    【解决方案2】:

    如果_commandListSystem.Collection.Generic.List<string> 类型,则可以使用以下sn-p:

    _commandList.AddRange(System.IO.File.ReadAllLines(fileName));
    

    完整代码:

    private void CommandFileSelectButton_Click(object sender, EventArgs e)
    {
        Stream mystream;
        OpenFileDialog commandFileDialog = new OpenFileDialog();
    
    
        if (commandFileDialog.ShowDialog() == DialogResult.OK)
        {
            if ((mystream = commandFileDialog.OpenFile())!= null)
            {
                string fileName = commandFileDialog.FileName;
                CommandListTextBox.Text = fileName;
                _commandList.AddRange(System.IO.File.ReadAllLines(fileName));
                CommandListListBox.DataSource = _commandList;
            }
    
        }
    }
    

    【讨论】:

      【解决方案3】:

      试试这个!

      // Open the file to read from. 
       string[] readText = File.ReadAllLines(fileName);
              foreach (string fileText in readText)
              {
                  _commandList.Add(fileText);
              }
      

      【讨论】:

        猜你喜欢
        • 2023-03-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多