Featured Post

C# Essential Training : 00. Introduction

Powered by Blogger.

Blog Archive

Blog Archive

Blogger news

Blogger templates

Blogger templates

Archive for February 2014

Try ... Catch in C# .NET

C# has some inbuilt objects you can use to deal with any potential errors in your code. You tell C# to Try some code, and if can't do anything with it you can Catch the errors. Here's the syntax:
try
{
}
catch
{
}
In the code below, we're trying to load a text file into a RichTextBox called rtb:
try
{
rtb.LoadFile("C:\\test.txt");
}
catch (System.Exception excep)
{
MessageBox.Show(excep.Message);
}
First, note the extra backslash after C:
C:\\test.txt
The extra backslash is called an escape character. You need to escape a single backslash because C# doesn’t like you typing just one of them.
The code we want to execute goes between the curly brackets of try. We know that files go missing, however, and want to trap this "File not Found" error. We can do that in the catch part. Note what goes between the round brackets after catch:
System.Exception excep
Exception is the inbuilt object that handles errors, and this follows the word System (known as a namespace). After System.Exception, you type a space. After the space, you need the name of a variable (excep is just a variable name we made up and, like all variable names, you call it just about anything you like).
The code between the curly brackets of catch is this:
MessageBox.Show(excep.Message);
So we're using a message box to display the error. After the variable name (excep for us), type a dot and you'll see the IntelliSense list appear:
The IntelliSense list
If you just want to display the inbuilt system message, select Message from the list. When the programme is run, you'll see a message box like this:
Using the inbuilt System message
If you know the type of error that will be generated, you can use that instead:
catch (System.IO.FileNotFoundException)
{
MessageBox.Show("File not found");
}
To find out what type of error will be generated, use this:
catch (System.Exception excep)
{
MessageBox.Show( excep.GetType().ToString() );
}
The message box will tell you what system error is being generated. You can then use this between the round brackets of catch.
If you want to keep things really simple, though, you can miss out the round brackets after catch. In the code below, we're just creating our own error messages:
try
{
rtb.LoadFile("C:\\test.txt");
}
catch
{
MessageBox.Show("An error occurred");
}
You can add more catch parts, if you want:
try
{
rtb.LoadFile("C:\\test.txt");
}
catch
{
MessageBox.Show("An error occurred");
}
catch
{
MessageBox.Show("Couldn't find the file");
}
catch
{
MessageBox.Show("Or maybe it was something else!");
}
The reason you would do so, however, is if you think more than one error may be possible. What if the file could be found but it can't be loaded into a RichTextBox? In which case, have two catch blocks, one for each possibility.
There's also a Finally part you can add on the end:
try
{
rtb.LoadFile("C:\\test.txt");
}
catch (System.Exception excep)
{
MessageBox.Show(excep.Message);
}
finally
{
//CLEAN UP CODE HERE
}
You use a Finally block to clean up. (For example, you've opened up a file that needs to be closed.) A Finally block will always get executed, whereas only one catch will.
(NOTE: there is also a throw part to the catch blocks for when you want a more specific error, want to throw the error back to C#, or you just want to raise an error without using try … catch. Try not to worry about throw.)
We won't be using Try … Catch block too much throughout this book, however, because they tend to get in the way of the explanations. But you should try and use them in your code as much as possible, especially if you suspect a particular error may crash your programme.

Tag : ,

The Locals Window in C# .NET

The Locals Window keeps track of what is in local variables (variables you've set up in this chunk of code, and not outside it).
Add a new breakpoint, this time in the margins to the left of your IF statement. Run your programme again, and click the button. When you see the yellow highlighted line, click the Debug menu at the top of C#. From the Debug menu, click Windows > Locals. You should see the following window appear at the bottom of your screen:
The Locals Window
Keep pressing F10 and the values will change. Here's what is inside of the variables after a few spins round the loop:
The Locals Window showing what is inside of the variables
The variable i is now 3; letter is still "D", and LetterCount is still 0. Keep pressing F10 and go round the loop a few times. What do you notice? Keep your eye on what changes in your Locals window. The changes should turn red.
You should notice that the value in i changes but letter never moves on. It is "D" all the time. And that's why LetterCount never gets beyond 0. But why does it never move on?

Exercise I
Why does LetterCount never gets beyond 0? Correct the code so that your textbox displays the correct answer of 3 when the programme is run. HINT: think Substring and loops!


In the next part, we'll take a look at another tool in you can add to your debugging armoury - Try ... Catch statement.

Tag : ,

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.

Tag : ,

Logic Errors in C# .NET

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.

Tag : ,

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/13 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.
You'll see how to handle errors like this, soon. But there's one final error type you have to know about - Logic Errors.

Tag : ,

Debugging your C# Apps

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!
In the next part, we'll take a look at Run Time errors.

Tag : ,

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;
}

Exercise
Finish the code for your Radio Buttons by adding three more else … if parts. Display a user's favourite movie type in a message box. When you've completed this exercise, your message box should look something like ours below:
MessageBox 4
OK, let's move on from Checkboxes and Radio buttons. In the next section, we'll take a look at how to Debug your code.

Tag : ,

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:
The SaveFileDialog object appears at the bottom of Visual C#
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.

Tag : ,

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.

In the next lesson, you'll see how to add a Save As dialogue box to your C# programmes.

Tag : ,

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.

In the next part, you'll see how to use the Open File Dialogue box to insert a text file into your text boxes.

Tag : ,

- Copyright © Learning Programming Language - Skyblue - Powered by Blogger - Designed by Johanes Djogan -