Search code examples
c#listboxadditionusingstreamreader

Why is my listbox not getting populated?


I have this code but it's not working. I've tried several different versions but nothing is working. I'm a newbie and still don't understand everything.

    OpenFileDialog filedialog = new OpenFileDialog();

    private void button3_Click(object sender, EventArgs e)
    {

        filedialog.ShowDialog();
        filedialog.FileOk += filedialog_FileOk;
    }

    void filedialog_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
    {
        using (StreamReader myStream = new StreamReader(filedialog.FileName))
        {
            string line;
            // Read and display lines from the file until the end of  
            // the file is reached. 
            while ((line = myStream.ReadLine()) != null)
            {
                listBox1.Items.Add(line);
            }
        }
    }

I think there is a requirement for to much plain text in this editor.


Solution

  • You're adding the event handler after the call to ShowDialog() has returned. Move it to before and it might work.