5

I want to be able to open a .txt file up into a richtextbox in c# and also into a global variable i have made called 'notes' but don't know how to do this. This is the code i have at the moment:

OpenFileDialog opentext = new OpenFileDialog();
if (opentext.ShowDialog() == DialogResult.OK)
{
    richTextBox1.Text = opentext.FileName;
    Globals.notes = opentext.FileName;
}

Only problem is it doesn't appear in neither the richtextbox nor in the global varibale, and the global allows it to be viewed in another richtextbox in another form. So please can you help, with ideally the .txt file going into both,

Thanks

Chris Bacon
  • 995
  • 8
  • 30
  • 42

6 Answers6

9

Do you mean you want to have the text displayed or the filename?

richTextBox1.Text = File.ReadAllText(opentext.FileName); 
Globals.notes = richTextBox1.Text;

You probably also want to correct this to:

if (opentext.ShowDialog() == DialogResult.OK)
BlueVoodoo
  • 3,626
  • 5
  • 29
  • 37
1
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
    System.IO.StreamReader sr = new System.IO.StreamReader(openFileDialog1.FileName);
    richTextBox1.Text = sr.ReadToEnd();
    sr.Close();
}
Anatoliy Nikolaev
  • 22,370
  • 15
  • 69
  • 68
Ayush Giri
  • 11
  • 1
1

In c# there are not global variables. The closest thing you can get is to make the variable "public static". But a better solution would be to make it an instance variable of an object you have access to, for example your main window class.

codymanix
  • 28,510
  • 21
  • 92
  • 151
0

Try using this, I used it for a chat program and it works fine, you can set your timer rate to whatever you want. You also don't have to use a timer, you can have a button initiate the refresh of the rich text box.

    private void refreshRate_Tick(object sender, EventArgs e)
    {
        richTextBox1.Text = File.ReadAllText(@"path.txt");
    }

Hope this helps!

MonkeyLogik
  • 87
  • 1
  • 1
  • 5
0

FileName property of OpenFileDialog control just gives the full path of file selected by user. In order to read the content of this file, you will need to use a method like File.ReadAllText.

Hemant
  • 19,486
  • 24
  • 91
  • 127
  • I'm using C# 2010 and i don't know it this could be the reason but it does not recognise File.ReadAllText for some reason, what do you think could this be? – Chris Bacon Dec 01 '10 at 17:31
  • Add 'using System.IO;'at the top of source file. – Hemant Dec 02 '10 at 02:56
0

I hope, I am not late. It seems like there is something like:

OpenFileDialog opentext = new OpenFileDialog();
if (opentext.ShowDialog() == DialogResult.OK)
{
    string selectedFileName = opentext.FileName;
    richTextbox.LoadFile(selectedFileName, RichTextBoxStreamType.UnicodePlainText);
}

Refs

Biplove Lamichhane
  • 3,995
  • 4
  • 14
  • 30