We'll now give users the option to add their own images to the
picture box, instead of the one we chose. To do that, you need to display an
Open File dialogue box when the user clicks your View > View Images
menu item.
Dialogue boxes in C# can be added with the aid of an inbuilt object. Have a
look in the Toolbox on the left hand side of Visual C#. There should be a category
called Dialogs:
All the dialogue boxes you are familiar with in Windows are on the list above.
The one highlighted is the one we want -
OpenFileDialog. Double click
this item, and you'll see a new item appear at the bottom of Visual C#, next
to your menuStrip1 object:
Nothing will appear on your form, however, because the Dialog controls are
are hidden from view. The one in the image above has a default Name of
openFileDialog1.
This is a bit long, so have a look at the Properties Window on the right. Change
the
Name to
openFD:
The control at the bottom of Visual C# should have changed, as well:
With the control selected, have another look at the Properties Window. You'll
see that there are Properties for
Filter,
FileName,
InitialDirectory
and
Title. We'll change these with code. But one important point to bear
in mind about the Open File Dialogue box is this: They don't actually open files!
What the Open File Dialogue box does, and the same is true for the other Dialog
controls, is to allow you to select a file for opening. You have to write separate
code to open anything. The only thing you're really doing here is to get at
a file name.
We want the dialogue box to appear when the
View > View Images menu
is clicked. So double click this item on your
View menu. A code stub
will appear:
To see the Open Dialogue box, add this line to your code, in between the curly
brackets:
openFD.ShowDialog();
So you type the Name of your control, and then a dot. After the dot, select
ShowDialog from the IntelliSense list. As its name suggest, this shows
you the dialogue box.
Run your programme and try it out. You should see something like the following
appear when you click your
View > View Images menu item:
Because we haven't yet set any Properties, a default location is displayed,
which is the Documents folder in Windows 7. The File name has the default openFileDialog1.
You can change all these, though.
We can set a Title, first. The default Title is the word Open, in white on
a blue background in XP, black on light blue background in Vista and Windows
7. Add this line to your code, before the first line:
openFD.Title = "Insert an Image";
This time, we're using the
Title Property, and setting it to the text
"Insert an Image". You can, of course, type anything you like here.
When you run your programme and click the menu item, the new Title will look
like this in XP:
And this in later versions of Windows:
If you wanted something more humorous, you could even change it something like
this:
Better to stick with something more descriptive, though!
Another thing you can change is that Look in area. The default location is
the Debug folder from your project. You can reset it with the InitialDirectory
property. Add the following line to your code, before the other two lines:
openFD.InitialDirectory = "C:";
We're setting the default folder to be C. This would assume that the user had
a hard drive called C. If you want to set the Initial Directory to the "My
Documents" folder of any computer, try this after the equals sign, instead
of "C:":
= System.Environment.GetFolderPath(Environment.SpecialFolder.Personal);
This will get the folder path to the My Document folder (Personal folder),
which is called the Documents folder in Vista and Windows 7. You need to do
it this way because different users will have different user names, and there's
no way for you to tell beforehand.
But run your programme and try it out. The Look in box should have changed
(XP):
Or this, in later versions of the Windows operating system:
For the File name area, you can use the
FileName Property. Add this
line to your code (add it before the final line):
openFD.FileName = "";
Here, we're setting the File Name to a blank string. Run your programme and
you'll find that the
File name area on your dialogue box will be blank,
and the cursor will be flashing away. Select any file you like, and the file
name will appear in the box.
The next thing to do is to set up some Files of type. This is for the drop
down list you see at the bottom, just under File name. Here's what we want to
do (XP):
And this in later versions of Windows:
So we want the user to be able to select JPEG images, GIF images, and Bitmap
images. When you set the files of type, you are restricting the type of files
that the user can open. This is done with the Filter Property. After all, you
don't want your users trying to insert text files into a picture box!
The filter property makes use of the pipe character ( | ). The pipe character
can be found above the backslash on a UK keyboard. Add this code, just before
the last line:
openFD.Filter = "JPEG|*.jpg";
Notice what comes after the equals sign:
"JPEG|*.jpg";
Your filters need to go between quote marks. But the JPEG part, before the
pipe character, is what you want to display in the drop down list. You can have
anything you like here, "JPEG Images" instead of just "JPEG",
for example. After the pipe character, you need an asterisk symbol * followed
by a dot. The asterisk symbol means "any file name". After the dot,
you type the file extension that you want to filter for.
Run you code and try it out. You should see this in the "Files of type"
list (on the right of the text box in Vista and Windows 7)::
Now change your code to this:
openFD.Filter = "JPEG Images|*.jpg";
The "Files of type" list will then look like this, depending on your
Operating System:
Using just one filter means that no other file types will display. To add other
file types you just need to use the pipe character again. Let's add GIF images,
as well. Change your code to this:
openFD.Filter = "JPEG Images|*.jpg|GIF Images|*.gif";
As you can see, the line is a bit messy! The new part is in blue, though. Notice
that you separate one file type from another with a pipe character. But you
also need a pipe to separate the text for the drop down list from the actual
file type. To add Bitmap images, the code would be this:
openFD.Filter = "JPEG Images|*.jpg|GIF Images|*.gif|BITMAPS|*.bmp";
In the line above, the three file types have been displayed using different
colours, so that you can see them better.
Here's a few more image types, and their file extensions:
TIFF Images: *.tif or *.tiff
PNG Images: *.png
PICT Images: *pct or *.pict
There are, of course, lots of others. In the image below, we've added TIFF
files to the list. (Note that you can use upper or lower case for the extensions.):
To display files of any type, use an asterisk symbol in place of the file extension.
For example:
openFD.Filter = "JPEG Images|*.jpg|All Files|*.*";
However, we still haven't inserted a new image. To place a selected image into
the picture box, you have to get the file name that the user selected. You can
add a string variable to your code for this:
string Chosen_File = "";
You then access the FileName property of openFD. Like this:
Chosen_File = openFD.FileName;
The file name will then be in the variable we've called
Chosen_File.
To place a new image into the picture box you have on the form, you need the
Image property:
pictureBox1.Image
To place your chosen file into the Image property, you need this:
pictureBox1.Image = Image.FromFile(Chosen_File);
So after the equals sign, you can use the
Image object. This has a method
called
FromFile( ). In between the round brackets of this method, you
type the name of the image file. For us, this image file is stored in our Chosen_File
variable.
Add the new lines to your code and your coding window should look something
like ours below (we've cut down on a few filters):
Run your programme and test it out. Select an image to open. You should find
that your new image replaces the old one in your picture box.
However, there is a problem with the code. Instead of clicking Open, click
Cancel. You should get an error message (C# 2012's error message is a
plain version of the one below):
Because the Cancel button was clicked, there is no image name in the variable
Chosen_File. So the programme "bugs out" on you. You need to handle
this in your code.
To check if the cancel button was clicked, you can use this:
if (openFD.ShowDialog() = = DialogResult.Cancel)
{
MessageBox.Show("Operation Cancelled");
}
So there is inbuilt object called
DialogResult. You check if this has
a value of
Cancel. Adding an else statement gives us this code:
Change your code so that it looks like ours above. When you run your programme
now, it shouldn't crash when you click the Cancel button.
You can also have this for you IF Statement, instead of the one above:
if (openFD.ShowDialog() != DialogResult.Cancel)
{
Chosen_File = openFD.FileName;
pictureBox1.Image = Image.FromFile(Chosen_File);
}
We've used the NOT symbol, here ( ! ). So we're checking if DialogResult does
NOT equal Cancel.
Open a Text File with the Open File Dialogue Box
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:
Double click to add a
RichTextBox to your form. You may have to adjust
the height and width of your form, and reposition other controls. But your form
should look like this, when you've added the RichTextBox:
The RichTextBox is the one at the bottom - it looks exactly the same as a normal
text box, but you can do more with it. One Method it does have is called
LoadFile(
). We'll use this to load a text file.
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:
We can add the same lines as before. So add this to your code:
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.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);
}
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.
Add a Save As Dialogue Box to your C# Programmes
Another useful Method you can use with the RichTextBox
is SaveFile( ). As its name suggests, this allows you to save the file
that's currently in the text box. We'll use this with another Dialog object.
This time, we'll use the SaveFileDialog control instead of the OpenFileDialog
control.
Return to you form, and locate the SaveFileDialog control in the Toolbox:
Double click to add one to your project. It should appear at the bottom of
your screen:
Click on
saveFileDialog1 to select it. Now have a look at the Properties
on the right hand side of the screen. Change the
Name property to
saveFD:
Now go back to your
File menu, on your Menu Strip. Click on
File,
then double click your
Save menu item. This will open up the code for
this item:
The code to add a Save option is practically the same as for the Open menu
item. Instead of saying openFD, though, it's saveFD. Here it is:
You should be able to work out what's happening, in the code above. The line
that does the saving is this one:
richTextBox1.SaveFile(Saved_File, RichTextBoxStreamType.PlainText);
Again, though, there is a better way to manipulate files. You'll learn all about
how to handle text files in a later section. For now, add the code above and
Run your programme. Click your
File > Open menu item to add a text
file to your Rich Text Box. Makes some changes to the text. Then click your
File > Save menu item. You should find that the changes are permanent.
OK, let's move on from menus. In the next section, we'll take a look at CheckBoxes
and Radio Buttons