Search code examples
c#winformstextrichtextboxopenfiledialog

opening a .txt in a windows form richtextbox


There is a question like this: Open a .txt file into a richTextBox in C#

But I need something a little different, I can open the txt in a richTextBox but I am using a button to make the file open. I want to skip the button and just have it load in the richTextBox.

Here is the button code, how do I move it to the richTextBox?:

private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.FileName = "Changes.txt";

            string strfilename = openFileDialog1.FileName;
            string filetext = File.ReadAllText(strfilename);

            richTextBox1.Text = filetext;
        }

        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {

        }

By double clicking the rich I get richTextBox1_TextChanged:

enter image description here


Solution

  • How about the load event of the Form?

    private void form_load(object sender, Eventargs e)
    {
         OpenFileDialog openFileDialog1 = new OpenFileDialog();
         openFileDialog1.FileName = "Changes.txt";
    
         string strfilename = openFileDialog1.FileName;
         string filetext = File.ReadAllText(strfilename);
    
         richTextBox1.Text = filetext;
    }
    

    I'm not sure what you want to do in the richTextBox1_TextChanged event, maybe you could provide more information regarding this.

    Having seen your edit, your'e still better off using the button to open the dialog and selecting a file that way. More intuitive then selecting the RichTextBox to trigger the OpenFileDialog.