質問

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

役に立ちましたか?

解決

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.

他のヒント

From what I understand, you are probably searching for the event RichTextBox_Click. In your form.cs design view, click your RichTextBox and press F4 to see its properties and click the thunderbolt icon to see its events. Search for "Click" and then double click it. That will create the click event in your class, and you can add your logic there.

modify your code with this. when dialogbox visible select the text file which you named here as "Changes.txt".

    private void button1_Click(object sender, EventArgs e)
    {
        OpenFileDialog openFileDialog1 = new OpenFileDialog();
        openFileDialog1.FileName = "Changes.txt";
        openFileDialog1.ShowDialog();
        string strfilename = openFileDialog1.FileName;
        string filetext = File.ReadAllText(strfilename);

        richTextBox1.Text = filetext;
    }
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top