Blogger templates

Pages

This is default featured post 1 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.This theme is Bloggerized by Lasantha Bandara - Premiumbloggertemplates.com.

This is default featured post 2 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.This theme is Bloggerized by Lasantha Bandara - Premiumbloggertemplates.com.

This is default featured post 3 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.This theme is Bloggerized by Lasantha Bandara - Premiumbloggertemplates.com.

This is default featured post 4 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.This theme is Bloggerized by Lasantha Bandara - Premiumbloggertemplates.com.

This is default featured post 5 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.This theme is Bloggerized by Lasantha Bandara - Premiumbloggertemplates.com.

Tuesday 22 October 2013

Understanding C# Methods

So far, all of your programming code has gone between the curly brackets of buttons. But this is not an effective way to programme. If you keep all your code in one place, it will become more and more unreadable the longer it gets. Instead, you can use something called a Method.
A Method is just a segment of code that does a particular job. Think about the calculator programme you have been working on. You can have one Method ( a chunk of code) to add up, one to subtract, another one to divide, and a fourth Method to multiply. The idea is that when you want to add up, you just call the Add Up Method into action.
To get you started with Methods, we'll create a simple programme that takes two numbers from text boxes. We'll have four buttons, one to add up, one to subtract, one to divide, and one to multiply. We'll use Methods to do the calculating. Off we go then!
Create a new C# project, and design the following form:
Design this C# form
You can keep the buttons and text boxes on their default names (button1, button2, textbox1, textbox2, etc.)
Double click the Add Up button to open up the coding window. The cursor will be flashing inside of the button code. However, you create Methods outside of any other code. So move the cursor after the final curly bracket of the button code. Then hit your enter key a few times to give yourself some space. Type the following:
void AddUp()
{
MessageBox.Show("Add Up Here");
return;
}
Your coding window will then look like ours below:
The Method is added outside of the button code
Methods can return a value, such as the answer to the addition. But they don't have to. Our Method above just displays a message box when it is called into action. If you don't want anything back from your Methods, you set them up by typing the keyword void. After a space, you need to come up with a name for your Method. We've called ours AddUp. But they are just the same as variable names, and you call them almost anything you like. (The same rules apply to naming Methods as they do to naming Variables.)
After coming up with a name for your Method, you type a pair of round brackets. You can put things between the round brackets, and you'll see how to do that shortly.
After the round brackets, you need a pair of curly brackets. The code for your Method goes between the curly brackets. For us, this was just a Message Box.
Before the final curly bracket, we've typed the word return, followed by a semicolon. This is not necessary, if you've set your Method up as void, since you don't want it to return anything: you just want it to get on with its job. We've added the return keyword because it's just standard practice. But when C# sees the return keyword, it will break out of your Method. If you type any code after that, it won't get executed. (You'll see a different way to use the return keyword when we want to get something back from a Method.)


Calling your Methods

Our Method is not doing much good at the moment, since it's not being called into action anywhere. We'll get it to do its work when a button is clicked.
To call a Method, you just do this:
AddUp();
So you type the name of your Method, along with the round brackets. The semicolon ends the line of code, as normal.
So add that line to your button that Adds Up:
Call the Method
Run your programme and test it out. Click the Add Up button and you should see the message box display.
What happens is that the button calls the AddUp Method into action. C# then trots off and executes all of the code for your Method. It then comes back to the line where it was called, ready to execute any other code you may have for your button.

Passing values to your C# Methods

You can hand values over to your Methods. The Method can then use these values in its code. For us, we want to get two numbers from the text boxes, and then add them up. The two values from the text boxes, then, need to be handed over to our Method. The code to add up will go between the curly brackets of the AddUp Method.
To hand values over to your Methods, you place them between the round brackets. These are called parameters. (You'll also hear the term arguments, often used to mean the same thing. There is a subtle difference, however, which you'll see shortly. It's not crucial that you learn the difference, though!)
Change your Method to this:
The method has two parameters
So we've added two parameters between the round brackets of AddUp. A parameter is set up just like an ordinary variable. You start with the variable type (int, string, bool, etc.) then a space. After the space, you need to come up with a name for your parameter. We've called our first parameter firstNumber. But we could have called it almost anything. If you want more than one parameter, you separate them with commas. We've added a second parameter and called it secondNumber. Both parameters have been set up as type int. They're going to hold numbers, in other words.
We can use these parameters in the code for the Method. Adapt your AddUp code so that it's like ours below:
Change your code
So we've set up a new int variable called answer. We're then adding up the variables firstNumber and secondNumber. The result goes in the new variable. The message box displays what is in the variable called answer.
If you try to run your code now, however, you'll get an error. There will be a wavy blue line under AddUp, along with a strange error message:
Argument error
This error message can be translated as "You have no Method called AddUp that takes zero arguments." When you're calling a Method into action, you need to use the same number of parameters (now called arguments instead) as when you set it up. We set up our Method to take two values, firstNumber and secondNumber. So we need to use two values when we call the Method.
Here's the difference between an argument and a parameter: It's a parameter when you set up the values in the method; It's an argument when you're calling it (passing the values to the Method).
Change your button code to this:
The method now has two arguments
So we've now typed two number between the round brackets, 15 and 5. The first value you type will get handed to parameter one of your Method, the second value will get handed to parameter two, and so on. The picture below might clear things up, if all of that is a little confusing:
Arguments and Parameters
So the Method itself has two parameters. When it is being called in the button code there are now two arguments, once for each parameter.
Run your programme again and there shouldn't be any errors. When you click your button, you should see the answer to the addition.
Halt your programme, and change your button code to this:
Change your code
Now, the values between the round brackets are no longer numbers that we've just typed in there. Instead, we're getting the values from the text boxes, and placing them between the round brackets. Note the comma separating the two values.
You can also do this:

We're now putting the values from the text boxes into two new variables, called number1 and number2. When we call the Method, we can use these variable names:
AddUp( number1, number2 );
The values in these two variables will get handed to our Method. But all you are trying to do is to pass two integers over to your Method. You need two integers because that's the way you set the Method up.
One more thing to note, here. When we set the Method up, the two parameters were called firstNumber and secondNumber. When we called it from the button, however, the two variables are called number1 and number2. So we've used different variables names. This is perfectly OK, and C# doesn't get confused. All that matters is that you are passing the correct information over to the Method.

Getting values back from C# Methods

The Method we set up used the keyword void. We used void because we didn't want anything back from the Method. But quite often you will want something back from your Methods.
What we'll do now is to use the Subtract button and deduct one text box number from the other. We'll set up another Method called Subtract. This time, we'll set it up so as to return an answer.
If you want to return a value from your Methods, you can't use the keyword void. Simply because void means "Don't return an answer". Instead of using void, we'll use the keyword int.
Add the following Method to your code, either above or below the AddUp Method:
A Method that returns a value
If you add a few comments, your coding window should look like ours:
What your coding window should look like
So we have one button and two Methods. Before we explain the new Method, double click the Subtract button on your form to get at its code. Then add the following:
Add this code
We'll explain how this button code works in a moment. But run your programme and you should see a message box appear when you click your Subtract button. Hopefully it will have the right answer!
Now have a look at the first line of the new Method:
private int Subtract( int firstNumber, int secondNumber)
The part in round brackets is exactly the same as before, and works the same way - set up the Method to accept two integer values. What's new is this part:
private int Subtract
Subtract is just the name of the Method, something we came up with ourselves. Before the Method name, however, we have two new keywords - private and int.
What we want our Method to do is to bring back the answer to our subtraction. The answer will obviously be a number. And that's why int comes before the Method name: we want the answer to the Subtract Method to be an integer. If you want to return values from your Methods they need what's called a return type. This is a variable like int, float, string, bool, etc. What you're telling C# to do is to return an int (or a bool, or a float).
Have a look at the whole Method again:

A Method that returns a value
Notice the final line:
return answer;
This means, "return whatever is inside of the variable called answer."
But where is C# returning to? Here's the code for the Subtract button again. The important line is in blue bold below:
private void button2_Click(object sender, EventArgs e)
{
int number1;
int number2;
int returnValue = 0;
number1 = int.Parse(textBox1.Text);
number2 = int.Parse(textBox2.Text);
returnValue = Subtract(number1, number2);
MessageBox.Show(returnValue.ToString());
}
When you click the button on the form, C# moves down line by line. When it gets to this line:
returnValue = Subtract( number1, number2 );
it will trot off and locate the Method called Subtract. It will then try to work out the code for the Method. Once it has an answer, it comes back to the same place. We have the call to the Method after an equals sign. Before the equals sign we have a new integer variable, which we've called returnValue. C# will store the answer to the Subtract Method inside of this returnValue variable. In other words, it's just like a normal variable assignment: work out the answer on the right of the equals sign, and store it on the left. In case that's not clear, these diagrams may help:
Step 1
Step 2
Step 3
Step 4
Step 5
After those steps, C# then drops down to the next line, which for us is a message box.
It can be tricky trying to follow what the method is doing, and what gets passed back. But just remember these points:

  • To set up a Method that returns a value, use a return type like int, float, bool, string, etc
  • Use the keyword return, followed by the answer you want to have passed back
  • Store the answer to your Method in another variable, which should come before an equals sign
One thing we haven't explained is why we started our Method with the word private.
Private refers to which other code has access to the Method. By using the private keyword you're telling C# that the Method can't be seen outside of this particular class. The class in question is the one at the top of the code, for the form. This one:
public partial class Form1 : Form
An alternative to private is public, which means it can be seen outside of a particular class or method. (There's also a keyword called static, which we'll cover later in the course.)


 


 

Debugging your C# Apps and Run Time Errors in C# .NET,Logic Errors

Debugging refers to the process of trying to track down errors in your programmes. It can also refer to handling potential errors that may occur. There are three types of errors that we'll take a look at:
  • Design-time errors
  • Run-Time errors
  • Logical errors
The longer your code gets, the harder it is to track down why things are not working. By the end of this section, you should have a good idea of where to start looking for problems. But bear in mind that debugging can be an art in itself, and it gets easier with practice.

Errors at Design-Time

Design-Time errors are ones that you make before the programme even runs. In fact, for Design-Time errors, the programme won't run at all, most of the time. You'll get a popup message telling you that there were build errors, and asking would you like to continue.
Design-Time errors are easy enough to spot because the C# software will underline them with a wavy coloured line. You'll see three different coloured lines: blue, red and green. The blue wavy lines are known as Edit and Continue issues, meaning that you can make change to your code without having to stop the programme altogether. Red wavy lines are Syntax errors, such as a missing semicolon at the end of a line, or a missing curly bracket in an IF Statement. Green wavy lines are Compiler Warnings. You get these when C# spots something that could potentially cause a problem, such as declaring a variable that's never used.

Blue Wavy Lines

In the image below, you can see that there's a blue wavy line under textBox2 (later versions of Visual Studio may have red wavy lines, instead of blue ones):
Blue Wavy Underline in C#
This is an Edit and Continue error. It's been flagged because the form doesn't have a control called textBox2 - it's called textBox1. We can simply delete the 2 and replace it with a 1. The programme can then run successfully. Holding your mouse over the wavy underline gives an explanation of the error. Some of these explanations are not terribly helpful, however!

Red Wavy Lines

These are Syntax errors. (Syntax is the "grammar" of a programming language, all those curly brackets and semicolons. Think of a Syntax error as the equivalent of programming spelling mistake.)
In the code below, we've missed out the semicolon at the end of the line:

Red Wavy Underline in C#
Holding the mouse pointer over the red wavy line gives the following message:
C# Error Explanation
It's telling us that a semicolon ( ; ) is expected where the red wavy underline is.
In the next image, we've missed out a round bracket for the IF Statement:
A Syntax Error in C#

Green Wavy Lines

These are Compiler Warnings, the C# way of alerting you to potential problems. As an example, here's some code that has a green wavy underline:
Green Wavy Underline
Holding the mouse pointer over the green underlines gives the following message:
Compiler Warning in C#
C# is flagging this because we have set aside some memory for the variable, but we're not doing anything with it.
This one is easy enough to solve, but some Compiler Errors can be a bit of a nuisance, and the messages not nearly as helpful as the one above!

Whatever the colour of the underline, though, the point to bear in mind is this: C# thinks it has spotted an error in your code. It's up to you to correct it!

Run Time Errors in C# .NET

Run-Time errors are ones that crash your programme. The programme itself generally starts up OK. It's when you try to do something that the error surfaces. A common Run-Time error is trying to divide by zero. In the code below, we're trying to do just that:
Divide by Zero Error
The programme itself reports no problems when it is started up, and there's no coloured wavy lines. When we click the button, however, we get the following error message (Visual Studio 2012 will have a plainer error message):
C# Error Message
Had we left this in a real programme, it would just crash altogether ("bug out"). But if you see any error message like this one, it's usually a Run-Time error. Here's another one. In the code below, we're trying to open a file that doesn't exist:
File Not Found Error
As the message explains, it can't find the file called "C:/test10.txt". Because we didn't tell C# what to do if there was no such file, it just crashes.
Look out for these type of error messages. It does take a bit of experience to work out what they mean; but some, like the one above, are quite straightforward.

Logical error
Logic errors are ones where you don't get the result you were expecting. You won't see any coloured wavy lines, and the programme generally won't "bug out" on you. In other words, you've made an error in your programming logic. As an example, take a look at the following code, which is attempting to add up the numbers one to ten:
A Logic Error in C#
When the code is run, however, it gives an answer of zero. The programme runs OK, and didn't produce any error message or wavy lines. It's just not the correct answer!
The problem is that we've made an error in our logic. The startLoop variable should be 1 and the endLoop variable 11. We've got it the other way round, in the code. So the loop never executes.
Logic errors can be very difficult to track down. To help you find where the problem is, C# has some very useful tools you can use. To demonstrate these tools, here's a new programming problem. We're trying to write a programme that counts how many times the letter "g" appears in the word "debugging".
Start a new C# Windows Application. Add a button and a textbox to your form. Double click the button, and then add the following code:

There's a logic error in this code
The answer should, of course, be 3. Our programme insists, however, that the answer is zero. It's telling us that there aren't and g's in Debugging. So we have made a logic error, but where?
C# .NET has some tools to help you track down errors like this. The first one we'll look at is called the BreakPoint.

Breakpoints in C# .NET

The first debugging tool we'll look at is the Breakpoint. This is where you tell C# to halt your code, so that you can examine what is in your variables. They are easy enough to add.
To add a Breakpoint, all you need to do is to click in the margins to the left of a line of code:
A Breakpoint in C# .NET
In the image above, we clicked in the margins, just to the left of line 21. A reddish circle appears. Notice too that the code on the line itself gets highlighted.
To see what a breakpoint does, run your programme and then click your button. C# will display your code:

The Breakpoint has been activated
There will be a yellow arrow on top of your red circle, and the line of code will now be highlighted in yellow. (If you want to enable line numbers in your own code, click Tools > Options from the C# menus at the top. On the Options box, click the plus symbol next to Text Editor, then C#. Click on General. On the right hand side, check the box for Line Numbers, under the Display heading.)
Press F10 on your keyboard and the yellow arrow will jump down one line. Keep pressing F10 until line 28 in your code is highlighted in yellow, as in the image below:

Line 28 is now being examined
Move your mouse pointer over the letter variable and C# will show you what is currently in this variable:
The letter variable is being examined
Now hold your mouse over strText to see what is in this variable:
Hold your mouse over the strText variable
Although we haven't yet mentioned anything about the Substring method, what it does is to grab characters from text. The first 1 in between the round brackets means start at letter 1 in the text; the second 1 means grab 1 character. Starting at letter 1, and grabbing 1 character from the word Debugging, will get you the letter "D". At least, that's what we hoped would happen!
Unfortunately, it's grabbing the letter "e", and not the letter "D". The problem is that the Substring method starts counting from zero, and not 1.
Halt your programme and return to the code. Change your Substring line to this:
letter = strText.Substring(0, 1);
So type a zero as the first number of Substring instead of a 1. Now run your code again:
The correct letter is in the variable
This time, the correct letter is in the variable. Halt your programme again. Click your Breakpoint and it will disappear. Run the programme once more and it will run as it should, without breaking.
So have we solved the problem? Is the programme counting the letter g's correctly?
No! The letter count is still zero! So where's the error? To help you track it down, there's another tool you can use - the Locals Window.

 

 

C# .NET - Checkboxes and Radio Buttons

Checkboxes and Radio Buttons are way to offer your users choices. Checkboxes allow a user to select multiple options, whereas Radio Buttons allow only one. Let's see how to use them.
Start a new project. When your new form appears, make it nice and big. Because Checkboxes and Radio Buttons are small and fiddly to move around, its best to place them on a Groupbox. You can then move the Groupbox, and the Checkboxes and Radio Buttons will move with them.
Locate the Groupbox control in the Toolbox on the left, under Containers. It looks like this:

The GroupBox Control in C# .NET
Draw one out on your form. Locate the Text property in the properties window on the right of C#. Change the Text property to What Type of Movies Do You Like?.
Add a second Groupbox along side of the first one, and set the Text property as And Your Favourite Is?. Your form will then look like this:
Two C# GroupBoxes on a  form
We'll place some Checkboxes on the first Groupbox, and some Radio Buttons on the second one.
Locate the Checkbox control on the toolbox, under Common Controls. Draw one out on your first Groupbox.
In the properties area on the right, notice that the default Name property is checkBox1. Leave it on this, but locate the Text property and change it to Comedy:

Adding a CheckBox to a form in C#
Draw four more checkboxes on the Groupbox, and set the Text properties as follows: Action, Science Fiction, Romance, Animation. (You can copy and paste the first one, instead of drawing them out.) Make the Text bold, and your Groupbox should look like this:
CheckBoxes on a GroupBox in C#
You add Radio Buttons in the same. So add five Radio Buttons to the second Groupbox. Leave the Name property on the defaults. But change the Text to the same as for the Checkboxes. Your form should look like ours below when you are finished:
Two GroupBoxes with CheckBoxes added
Now add two buttons, one below each group box. Set the Text for the first one as Selected Movies. Set the Text for the second one as Favourite Movie. Here's what your form should look like now:
What your form should look like
Run your form and test it out. What you should find is that you can select as many checkboxes as you like, but only one of the Radio Buttons.
Stop your programme and return to Design Time.
What we'll do now is to write code to get at which selections a user made. First, the Checkboxes.
Double click your Selected Movies button to open up the code window. Our code will make use of the Checked property of Checkboxes. This is either true or false. It will be true if the user places a check in the box, and false if there is no check.
We can use if statements to test the values of each checkbox. We only need to test for a true value:
if (checkBox1.Checked)
{
}
We can also build up a message, if an option was selected:
string movies = "";
if (checkBox1.Checked)
{
movies = movies + checkBox1.Text;
}
MessageBox.Show(movies);
Inside of the if statement, we are building up the string variable we've called movies. We're placing the Text from the Checkbox into this variable.
Add a second if statement to your code:
string movies = "";
if (checkBox1.Checked)
{
movies = movies + checkBox1.Text;
}
if (checkBox2.Checked)
{
movies = movies + checkBox2.Text;
}
MessageBox.Show(movies);
The second if statement is the same as the first, except it refers to checkBox 2 instead of checkBox1.
Test out your code so far. Run your programme and check both boxes. Click your button and the message box should display the following:
A C# MessageBox
As you can see, they are both on the same line, with no spacing.
Stop your programme and return to your code.
To get the choices on separate lines, there are a few ways you can do it. One way is to use the return and new line characters, like this:
movies = movies + checkBox1.Text + "\r\n";
The "\r" gets you a Return character, and the "\n" gets you a Newline character.
But you can also use the inbuilt Newline character. Like this:
movies = movies + checkBox1.Text + Environment.NewLine;
Newline is a property of the Environment class. As its name suggests, it adds a new line to your text.
Add one of the Newline options to both of your if statements, and then test it out. Your message box will look like this, with both options checked:
C# MessageBox with a Newline Character
Return to your code, and add three more if statements. When you are finished, your coding window should look like this one:
C# Code for CheckBoxes
When you run your programme and check all the boxes, the message box will look like this, after the button is clicked:
MessageBox 3
To get at which Radio Button was chosen, the code is the same as for Checkboxes - just test the Checked stated. The only difference is that you need else if, instead of 5 separate if statements:
string ChosenMovie = "";
if (radioButton1.Checked)
{
ChosenMovie = radioButton1.Text;
}
else if (radioButton2.Checked)
{
ChosenMovie = radioButton2.Text;
}

Open File Dialogue Box in C#

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:
The Dialogs Tools in Visual C# .NET
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:
An OpenFileDialog control added to a form
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:
Change the Name Property to openFD
The control at the bottom of Visual C# should have changed, as well:
The Name has been changed
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:
C# code stub for a menu item
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:
The Open Dialogue Box
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:
The Title has changed
And this in later versions of Windows:
Changing the Title property
If you wanted something more humorous, you could even change it something like this:
A New Title
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):

Set the Look In area to the My Documents folder of XP
Or this, in later versions of the Windows operating system:
InitialDirectory property
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):
Set the Files of Type
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)::
Filtering for JPEG images in C#
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:
Files of Type now reads JPEG Images
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.):
Four Image types have been filtered for
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):
C# code for the View Images menu item
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):
ArgumentException Error
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:
The complete 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:
The RichTextBox control in C# .NET
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:
A RichTextBox control on a Windows Form
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:
The Open code stub
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:
The SaveFileDialog control in Visual C# .NET
Double click to add one to your project. It should appear at the bottom of your screen:
The SaveFileDialog object appears at the bottom of Visual C#
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:
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 Save code stub
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:
The complete Save code
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