user3598883
user3598883

Reputation: 47

How to get a Listbox to read to a Listbox

I am trying to open any selected textfile and have the text input be sent to a listbox... Originally I wrote this code for a textbox which worked great now that I am converting it to a listbox it doesnt seem to work so much. I left the default item names in order for better understanding of what is going on.

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

Upvotes: 0

Views: 90

Answers (5)

Mark Smit
Mark Smit

Reputation: 574

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

Upvotes: 0

Jyrka98
Jyrka98

Reputation: 530

string[] lines = File.ReadLines("SomeFile.txt").ToArray();
foreach (var line in lines)
{
    listBox1.Items.Add(line);
}

Upvotes: 0

Xiaoy312
Xiaoy312

Reputation: 14477

Try this :

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

Upvotes: 1

Brandon
Brandon

Reputation: 645

.Add() is a method and you are treating it like a property.

Try this code instead:

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

Upvotes: 0

Chiro300
Chiro300

Reputation: 76

listBox1.Items.AddRange(File.ReadAllLines(label1.Text));

Upvotes: 1

Related Questions