We can reuse the Open File dialogue box that we have added. Instead
of filtering for images, we'll filter for text files. We'll also add a different
kind of text box - the Rich Text Box. This will allow us to easily add the text
from the file, straight into the programme.
So return to Designer View, so that you can see your form. Now expand the Toolbox,
and locate RichTextBox, under Common Controls:Now that we've added the RichTextBox, we can add some code. So, access the code stub for you File > Open menu item. It should look like this:
string Chosen_File = "";
openFD.InitialDirectory = "C:";
openFD.Title = "Open a Text File";
openFD.FileName = "";
The only thing we've changed here is the Title property. For the next line,
we can add the Filters:openFD.Title = "Open a Text File";
openFD.FileName = "";
openFD.Filter = "Text Files|*.txt|Word Documents|*.doc";
The RichTextBox can open plain text files as well as Word documents, so we've
added both of these to the Filter property. (It can't handle Word documents
very well, though.)The next thing to do is to display the Open File Dialogue box, so that a file can be selected. Add the following to your code:
if (openFD.ShowDialog() != DialogResult.Cancel)
{
{
Chosen_File = openFD.FileName;
richTextBox1.LoadFile(Chosen_File, RichTextBoxStreamType.PlainText);
richTextBox1.LoadFile(Chosen_File, RichTextBoxStreamType.PlainText);
}
This is more or less the same as before. But notice the line that adds the
text file to RichTextBox:
richTextBox1.LoadFile(Chosen_File, RichTextBoxStreamType.PlainText);
You'll see a better way to open up a text file later in the course. For now,
run your programme and test that it works. You should be able to add plain text
file to the RichTextBox. In the next lesson, you'll see how to add a Save As dialogue box to your C# programmes
0 comments:
Post a Comment