The_Monster
The_Monster

Reputation: 510

Fill Listbox with values from TextFile

i have a issue with my code. My code has to read out values from a textfiles, which it does. But when i put the values of the textfile in my listbox it comes out like this:

commandlistbox

So the commands or values are coming in one line. I want the commands to go like this, I've changed the picture so you can see:

enter image description here

So you see? I want the commands under each other. This is my code for reading the textfile:

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 is an local functions which my co worker has made.

This is how to TextFile looks:

RUN 
RUNW
STOP
RUN
RUN
STOP

Thanks in advance for the help.

Upvotes: 1

Views: 1129

Answers (3)

jiten
jiten

Reputation: 5264

Try this !

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

Upvotes: 2

SynerCoder
SynerCoder

Reputation: 12766

If _commandList is of type System.Collection.Generic.List<string> you can use the following snippet:

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

Full code:

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;
        }

    }
}

Upvotes: 2

Damith
Damith

Reputation: 63065

CommandListListBox.DataSource = File.ReadAllLines(fileName);

Upvotes: 3

Related Questions