Saturday, 25 May 2013


The only thing we'll do with the code is to write some text to the screen. But here's the code that Visual C# prepares for you when you first create a Console Application:


For now, ignore the lines that start with using as we'll get to them later in the course. (The image above is from version 2012 - earlier versions will have fewer using lines) But they add references to in-built code. The namespace line includes the name of your application. A namespace is a way to group related code together. Again, don't worry about the term namespace, as you'll learn about these later.

The thing that's important above is the word class. All your code will be written in classes. This one is called Program (you can call them anything you like, as long as C# hasn't taken the word for itself). But think of a class as a segment of code that you give a name to.

Inside of the class called Program there is this code:

static void Main(string[] args)
{

}

This piece of code is something called a Method. The name of the Method above is Main. When you run your programme, C# looks for a Method called Main. It uses the Main Method as the starting point for your programmes. It then executes any code between those two curly brackets. The blue words above are all special words - keywords. You'll learn more about them in later chapters.

But position your cursor after the first curly bracket, and then hit the enter key on your keyboard:


The cursor automatically indents for you, ready to type something. Note where the curly brackets are, though, in the code above. You have a pair for class Program, and a pair for the Main method. Miss one out and you'll get error messages.

The single line of code we'll write is this (but don't write it yet):

Console.WriteLine("Hello C Sharp!");

First, type the letter "C". You'll see a popup menu. This popup menu is called the IntelliSense menu. It tries to guess what you want, and allows you to quickly add the item from the list. But it should look like this, after you have typed a capital letter "C":

C# 2010


 

Older versions of C#


The icon to the left of the word Console on the list above means that it is a Class. But press the Enter key on your keyboard. The word will be added to your code:


Now type a full stop (period) immediately after the word Console. The IntelliSense menu appears again:


You can use the arrow keys on your keyboard to move up or down the list. But if you type Write and then the letter L of Line, IntelliSense will automatically move down and select it for you:



Press the Enter key to add the word WriteLine to your code:


Now type a left round bracket. As soon as you type the round bracket, you'll see this:


WriteLine is another Method (A Method is just some code that does a particular job). But the yellow box is telling you that there are 19 different versions of this Method. You could click the small arrows to move up and down the list. Instead, type the following:

"Hello C Sharp!"

Don't forget the double quotes at the start and end. These tell C# that you want text. Your code will look like this:


Now type a right round bracket:


Notice the red wiggly line at the end. This is the coding environment's way of telling you that you've missed something out.

The thing we've missed out is a semicolon. All complete lines of code in C# must end with a semicolon. Miss one out and you'll get error messages. Type the semicolon at the end and the red wiggly line will go away. Your code should now look like this:


Note all the different colours. Visual C# colour-codes the different parts of your code. The reddish colour between double quotes means that you want text; the green colour means it's a Class; blue words are ones that C# reserves for itself.

(If you want, you can change these colours. From the menu bar at the top, click Tools > Options. Under Environment, click Fonts and Colors.)

Time now to Build and Run your code!

What we want to do now is to display a message box whenever the button is clicked. So we need the coding window. To see the code for the button, double click the button you added to the Form. When you do, the coding window will open, and your cursor will be flashing inside of the button code. It will look like this:


The only difference from the last time you saw this screen is the addition of the code for the button. This code:

private void button1_Click(object sender, EventArgs e)
{

}

This is just another Method, a piece of code that does something. The name of the Method is button1_Click. It's called button1 because that's currently the Name of the button. When you changed the Text, Location, and Size properties of the button, you could have also changed the Name property from button1 (the default Name) to something else.

The _Click part after button1 is called an Event. Other events are MouseDown, LocationChanged, TextChanged, and lots more. You'll learn more about Events later.

After _Click, and in between a pair of round brackets, we have this:

object sender, EventArgs e

These two are know as arguments. One arguments is called sender, and the other is called e. Again, you'll learn more about arguments later, so don't worry about them for now.

Notice that there is a pair of curly brackets for the button code:

private void button1_Click(object sender, EventArgs e)
{

}

If you want to write code for a button, it needs to go between the two curly brackets. We'll add a single line of code in the next part below.

We want to display a message box, with some text on it. This is quite easy to do in C#.

Position your cursor between the two curly brackets. Then type a capital letter "M". You'll see the IntelliSense list appear:


Now type "ess" after the "M". IntelliSense will jump down:


The only options that start with Mess are all Message ones. The one we want is MessageBox. You can either just type the rest, or even easier is to press the down arrow on your keyboard to move down to MessageBox:


When you have MessageBox selected, hit the enter key on your keyboard (or double click the entry on the list). The code will be added for you:


Now type a full stop (period) after the "x" of MessageBox. The IntelliSense list will appear again:


There are only three items on the list now, and all Methods (you can tell they are Methods because they have the purple block icon next to them) Double click on Show, and it will be added to your C# code:


Because Show is a Method, we need some round brackets. The text for our message box will go between the round brackets. So type a left round bracket, just after the "w" of "Show":


As soon as you type the left round bracket after the "w", you'll see all the different ways that the Show method can be used. There are 21 different ways in total. Fortunately, you don't have to hunt through them all! Type the following, after the left round bracket (Don't forget the double quotation marks.):

"My First Message"

After the final double quote mark, type a right round bracket. Then finish off the line by typing a semi-colon ( ; ), Your coding window will then look like this:


The text in the dark reddish colour is what will be displayed in your message box. To try it out, save your work by clicking File from the menu bar at the top of Visual Studio. From the File menu, click Save All. You'll then see the same Save box you saw for the Console Application. Save the project.

Run your programme by clicking Debug > Start Debugging. Or just press the F5 key on your keyboard. Your programme will look like this:


Click your button to see your Message Box:


Congratulations! It's your first message! In the next part, we'll explore other things you can do with a message box.

If you look at the message box we created in the previous section, you'll notice there's no Title in the blue area to the left of the red X - it's blank:


You can add a Title quite easily.

Click OK on your Message Box. Then click the Red X on your programme to exit it. This will return you to Visual C#. Go back to the coding window (press F7 on your keyboard, if you can't see it).

Position your cursor after the final double quote of "My First Message", circled in red in the image below:


Now type a comma. As soon as you type a comma, you'll see the list of Show options again:


Type the following:

"Message"

Again, you need the double quotes. But your line of code should look like this:


When your line of code looks like the one above, Run your programme again. Click your button and you should see a Title on your Message Box:


 

Other Button Options

Rather than having just an OK button, you can add buttons like Yes, No, and Cancel to your C# message boxes. We'll add a Yes and a No button.

Return to your coding window. After the second double quote of the Title you've just added, type another comma. Hit the spacebar on your keyboard once, and you'll see the IntelliSense list appear. (If it doesn't appear, just type a capital letter "M").


The one that adds buttons to a message box is, you won't be surprised to hear, MessageBoxButtons. Press the enter key on your keyboard when this option is highlighted. It will be added to the your code. Now type a full stop (period) after the final "s" of MessageBoxButtons. You'll see the button options:


Double click the one for YesNo, and it will be added to your code.

Run your programme again, and click your button. Your Message Box will then look like this:


 

Adding Icons to a C# Message Box

Another thing you can add to brighten up your Message Box is an Icon. It's easier to see what these are than to explain!

Type another comma after MessageBoxButtons.YesNo. After the comma, type a capital letter "M" again. From the IntelliSense list that appears, double click MessageBoxIcon. After MessageBoxIcon, type a full stop to see the available icons:


We've gone for Asterisk. Double click this to add it to your code. Run your programme again to see what the icon looks like on your Message Box:


Looks pretty impressive, hey! And all that with one line of code!

We'll move on to the important subject of variable, in the next part. First, try this Exercise.

 

Exercise
Try the other icons on the IntelliSense list, and see what they look like when your programme runs. Does the Information icon differ from the Asterisk? (To quickly display the IntelliSense list again, delete the word Asterisk from your code, then delete the full stop. Type the full stop again, and the IntelliSense list will reappear.)

Programmes work by manipulating data stored in memory. These storage areas come under the general heading of Variables. In this section, you'll see how to set up and use variables. You'll see how to set up both text and number variables. By the end of this section, you'll have written a simple calculator programme. We'll start with something called a String variable.

 

String Variables in C#.NET


The first type of variable we'll take a look at is called a String. String variables are always text. We'll write a little programme that takes text from a text box, store the text in a variable, and then display the text in a message box.

But bear in mind that a variable is just a storage area for holding things that you'll need later. Think of them like boxes in a room. The boxes are empty until you put something in them. You can also place a sticker on the box, so that you'll know what's in it. Let's look at a programming example.

If you've got your project open from the previous section, click File from the menu bar at the top of Visual C#. From the File menu, click Close Solution. Start a new project by clicking File again, then New Project. From the New Project dialogue box, click on Windows Application. For the Name, type String Variables.

Click OK, and you'll see a new form appear. Add a button to the form, just like you did in the previous section. Click on the button to select it (it will have the white squares around it), and then look for the Properties Window in the bottom right of Visual Studio. Set the following Properties for your new button:

Name: btnStrings
Location: 90, 175
Size: 120, 30
Text: Get Text Box Data

Your form should then look like this:


We can add two more controls to the form, a Label and a Text Box. When the button is clicked, we'll get the text from the text box and display whatever was entered in a message box.

A Label is just that: a means of letting your users know what something is, or what it is for. To add a Label to the form, move your mouse over to the Toolbox on the left. Click the Label item under Common Controls:


Now click once on your form. A new label will be added:


The Label has the default text of label1. When your label is selected, it will have just the one white square in the top left. When it is selected, the Properties Window will have changed. Notice that the properties for a label are very similar to the properties for a button - most of them are the same!

Change the following properties of your label, just like you did for the button:

Location: 10, 50
Text: Name

You don't really need to set a size, because Visual C# will automatically resize your label to fit your text. But your Form should look like this:


Move your mouse back over to the Toolbox. Click on the TextBox entry. Then click on your form. A new Text Box will be added, as in the following image:


Instead of setting a location for your text box, simply click it with your left mouse button. Hold your left mouse button down, and the drag it just to the right of the Label.

Notice that when you drag your text box around, lines appear on the form. These are so that you can align your text box with other controls on the form. In the image below, we've aligned the text box with the left edge of the button and the top of the Label.


OK, time to add some code. Before you do, click File > Save All from the menu bar at the top of Visual C#. You can also run your programme to see what it looks like. Type some text in your text box, just to see if it works. Nothing will happen when you click your button, because we haven't written any code yet. Let's do that now. Click the red X on your form to halt the programme, and you'll be returned to Visual C#.

Double click your button to open up the coding window. Your cursor will be flashing inside of the curly brackets for the button code:


Notice all the minus symbols on the left hand side. You can click these, and it will hide code for you. Click the minus symbol next to public Form1( ). It will turn into a plus symbol, and the code for just this Method will be hidden:


Hiding code like this makes the rest of the coding window easier to read. Back to the button code, though. We're going to set up a string variable. To do this, you need two things: the Type of variable you want, and a name for your variable.

Click inside the two curly brackets of the button code, and add the following:

string firstName;

After the semi-colon, press the enter key on your keyboard to start a new line. Your coding window will then look like this:


What you have done is to set up a variable called firstName. The Type of variable is a string. Note that the coding editor will turn the word "string" blue. Blue denotes the variable type - a string, in this case. (Other variable types are int, float, and double. These are all number variables that you'll meet shortly.)

After you have told C# which type of variable you want, you then need to come up with a name for your variable. This is like the sticker on an empty box. The empty box is the variable type. Think of these empty boxes as being of different sizes and different materials. A big, cardboard box is totally different from a small wooden one! But what you are really doing here is telling C# to set aside some memory, and that this storage area will hold strings of text. You give it a unique name so as to tell it apart from other items in memory. After all, would you be able to find the correct box, if they were all the same size, the same shape, the same colour, and had no stickers on them?

The name you pick for your variables, firstName in our case, can be almost anything you want - it's entirely up to you what you call them. But you should pick something that is descriptive, and gives you a clue as to what might be in your variable.

We say you can call your variables almost anything. But there are some rules, and some words that C# bags for itself. The words that C# reserves for itself are called Keywords. There are about 80 of these words, things like using, for, new, and public. If the name you have chosen for your variable turns blue in the coding window, then it's a reserved word, and you should pick something else.

 

Characters you can use for your Variables


The only characters that you can use in your variable names are letters, numbers, and the underscore character ( _ ). And you must start the variable name with a letter, or underscore. You'll get an error message if you start your variable names with a number. So these are OK:

firstName
first_Name
firstName2

But these are not:

1firstName (Starts with a number)
first_Name& (Ends with an illegal character)
first Name (Two words, with a space in between)

Notice that all the variable names above start with a lowercase letter. Because we're using two words joined together, the second word starts with an uppercase letter. It's recommended that you use this format for your variables (called camelCase notation.) So firstName, and not Firstname.

After setting up your variable (telling C# to set aside some memory for you), and giving it a name, the next thing to do is to store something in the variable. Add the following line to your code (don't forget the semi-colon on the end):

firstName = textbox1.Text;

Your coding window will then look like this:


To store something in a variable, the name of your variable goes on the left hand side of an equals sign. After an equals sign, you type what it is you want to store in the variable. For us, this is the Text from textbox1.

Except, there's a slight problem. Try to run your code. You should see an error message like this one:


Click No, and have a look at your code:


There is a blue wiggly line under textbox1. Hold your mouse over this and Visual Studio will tell you that:

The name 'textbox1' does not exist in the current context.

If you see an error like this, which is quite common, it means that Visual C# cannot find anything with the name you've just typed. So it thinks we don't have a textbox called textbox1. And we don't! It's called textBox1. We've typed a lowercase "b" when it should be an uppercase "B". So it's important to remember that C# is case sensitive. This variable name:

firstName

Is different to this variable name:

FirstName

The first one starts with a lowercase "f" and the second one starts with an uppercase "F".

Delete the lowercase "b" from your code and type an uppercase "B" instead. Run your programme again and you won't see the error message. Now stop your programme and return to the coding window. The blue wiggly line will have disappeared.

What have so far, then, is the following:

string firstName;
firstName = textBox1.Text;

The first line sets up the variable, and tells C# to set aside some memory that will hold a string of text. The name of this storage area will be firstName.

The second line is the one that actually stores something in the variable - the Text from a text box called textBox1.

Now that we have stored the text from the text box, we can do something with it. In our case, this will be to display it in a message box. Add this line to your code:

MessageBox.Show(firstName);

The MessageBox.Show( ) Method is one you've just used. In between the round brackets, you can either type text surrounded by double quotes, or you can type the name of a string variable. If you're typing the name of a variable, you leave the double quotes off. You can do this because C# knows what is in your variable (you have just told it on the second line of your code.)

Run your programme again. Type something in your text box, and then click the button. You should see the text you typed:


Halt your programme and return to the coding window.

 

Assigning text to a String Variable


As well as assigning text from a text box to your variable, you can assign text like this:

firstName = "Home and Learn";

On the right hand side of the equals sign, we now have some direct text surrounded by double quotes. This then gets stored into the variable on the left hand side of the equals sign. To try this out, add the following two lines just below your MesageBox line:

firstName = "Home and Learn";
MessageBox.Show(firstName);

Your coding window will then look like this:


Run your programme again. Type something in the text box, your own first name. Then click the button. You should see two message boxes, one after the other. The first one will display your first name. But the second will display "Home and Learn".

We're using the same variable name, here: firstName. The first time we used it, we got the text directly from the text box. We then displayed it in the Message Box. With the two new lines, we're typing some text directly in the code, "Home and Learn", and then assigning that text to the firstName variable. We've then added a second MessageBox.Show( ) method to display whatever is in the variable.

In the next part of this lesson, you'll learn about something called Concatenation.

Concatenation in C#



Another thing we can do is something called Concatenation. Concatenation is joining things together. You can join direct text with variables, or join two or more variables to make a longer string. A coding example may clear things up.

Delete the two new lines you've just added. Now add a second variable, just below the first one:

string messageText;

So you coding window should look like this:


We want to store some text inside of this new variable, so add the following line of code just below string messageText:

messageText = "Your name is: ";

Your code window will then look like ours below:


When the message box displays, we want it say some thing like "You name is John". The variable we've called messageText holds the first part of the string, "Your name is ". And we're getting the persons name from the text box:

firstName = textBox1.Text;

The person's name is being stored in the variable called firstName. To join the two together (concatenate) C# uses the plus symbol ( + ).

messageText + firstName

Instead of just firstName between the round brackets of MessageBox.Show( ), we can add the messageText variable and the plus symbol:

MessageBox.Show(messageText + firstName);

Amend your MessageBox line so it's the same as the one above. Here's the coding window:


Run your programme. Type your first name into the text box, and then click your button. You should see something like this:


So we set up a variable to hold some direct text, and got the person's name from the text box. We stored this information in two different variables. To join the two together, we used the plus symbol. We then displayed the result in a message box.

But you can also do this:

MessageBox.Show( "Your name is: " + firstName);

Here, we're not storing the text in a variable called messageText. Instead, it's just direct text surrounded by double quotes. Notice, though, that we still use the plus symbol to join the two together.

Comments in C# .NET



You don't have to use a message box to display the result. You can use other controls, like a Label. Let's try it.

Add a new Label to your form. Use the Properties Window to set the following properties for your new Label:

Name: TextMessage
Location: 87, 126
Text: Message Area

Return to your coding window, and add two forward slashes to the start of your MessageBox.Show( ) line. The line should turn green, as in the following image:


The reason it turns green is that two forward slashes are the characters you use to add a comment. C# then ignores theses lines when running the programme. Comments are a very useful way to remind yourself what the programme does, or what a particular part of your code is for. Here's our coding window with some comments added:


You can also use the menu bar, or the toolbar, to add comments. Highlight any line of text in your code. From the menu bar at the top of Visual C#, select Edit > Advanced > Comment Selection. Two forward slashes will be added to the start of the line. You can quickly add or remove comments by using the toolbar. Locate the following icons on the toolbars at the top of Visual C#:


In version 2012, the comment icons look like this:


The comment icons are circled in red, in the images above. The first one adds a comment, and the second one removes a comment. (If you can't see the above icons anywhere on your toolbars, click View > Toolbars > Text Editor.)

Now that you have commented out the MessageBox line, it won't get executed when your code runs. Instead, add the following like to the end of your code:

TextMessage.Text = messageText + firstName;

Your coding window should then look like this:


Run your programme again. Type your name in the text box, and then click your button. The message should now appear on your label, instead of in a Message Box:


The reason is does so is because you're now setting the Text property of the Label with code. Previously, you changed the Label's Text Property from the Properties Window. The name of our label is TextMessage. To the right of the equals sign, we have the same code that was in between the round brackets of the Show( ) method of the MessageBox.

OK, time for an exercise.


Exercise
Add a second text box to your form. Display your message in the text box as well as on the label. So if your name is John, your second text box should have: "Your name is: John" in it after the button is clicked.


When you complete this exercise, your form should look like this, when the button is clicked:


We’re now going to move away from string variables and on to number variables. The same principles you’ve just learnt still apply, though:

  • Set up a variable, and give it a name
  • Store something in the variable
  • Use code to manipulate what you have stored

·         As well as storing text in memory you can, of course, store numbers. There are a number of ways to store numbers, and the ones you'll learn about now are called Integer, Double and Float. First up, though, are Integer variables.

·         First, close any solution you have open by clicking File > Close Solution from the menu bar at the top of Visual Studio. Start a new project by clicking File > New Project. From the New Project dialogue box, select Windows Forms Application from the available templates. Type a Name for your project. Call it Numbers.

·         Click OK, and you'll have a new form to work with.

·          

·         C# Integers


·         An integer is a whole number. It's the 6 of 6.5, for example. In programming, you'll work with integers a lot. But they are just variables that you store in memory and want to manipulate. You'll now see how to set up and use Integer variables.

·         Add a button to your form, and set the following properties for it in the Properties Window:

·         Name: btnIntegers
Text: Integers
Location: 110, 20

·         Now double click your button to get at the code:

·        

·         In the previous section, you saw that to set up a string variable you just did this:

·         string myText;

·         You set up an integer variable in the same way. Except, instead of typing the word string, you type the word int (short for integer).

·         So, in between the curly brackets of your button code, type int. You should see the word turn blue, and the IntelliSense list appear:

·        

·         Either press the enter key on your keyboard, or just hit the spacebar. Then type a name for your new variable. Call it myInteger. Add the semi-colon at the end of your line of code, and hit the enter key. Your coding window will then look like this:

·        

·         Notice the text in the yellow box, in the image one up from the one above. It says:

·         Represents a 32-bit signed integer

·         A signed integer is one that can have negative values, like -5, -6, etc. (The opposite, no negative numbers, is called an unsigned integer.) The 32-bit part is referring to the range of numbers that an integer can hold. The maximum value that you can store in an integer is: 2,147,483,648. The minimum value is the same, but with a minus sign on the front: -2,147,483,648.

·         To store an integer number in your variable, you do the same as you did for string: type the name of your variable, then an equals sign ( = ), then the number you want to store. So add this line to your code (don't forget the semi-colon on the end):

·         myInteger = 25;

·         Your coding window should look like this:

·        

·         So we've set up an integer variable called myInteger. On the second line, we're storing a value of 25 inside of the variable.

·         We'll use a message box to display the result when the button is clicked. So add this line of code for line three:

·         MessageBox.Show(myInteger);

·         Now try to run your code. You'll get the following error message:

·        

·         You should see a blue wiggly line under your MessageBox code:

·        

·         Hold your mouse over myInteger, between the round brackets of Show( ). You should see the following yellow box:

·        

·         The error is: "Cannot convert from int to string". The reason you get this error is because myInteger holds a number. But the MessageBox only displays text. C# does not convert the number to text for you. It doesn't do this because C# is a programming language known as "strongly typed". What this means is that you have to declare the type of variable you are using (string, integer, double). C# will then check to make sure that there are no numbers trying to pass themselves off as strings, or any text trying to pass itself off as a number. In our code above, we're trying to pass myInteger off as a string. And C# has spotted it!

·         What you have to do is to convert one type of variable to another. You can convert a number into a string quite easily. Type a full stop (period) after the "r" of myInteger. You'll see the IntelliSense list appear:

·        

·         Select ToString from the list. Because ToString is a method, you need to type a pair of round brackets after the "g" of ToString. Your code will then look like this (we've highlighted the new addition):

·        

·         The ToString method, as its name suggests, converts something to a string of text. The thing we are converting is an integer.

·         Start your programme again. Because you've converted an integer to a string, you should find that it runs OK now. Click your button and you should see the message box appear:

·        

·         In the next lesson, we'll take a look at double variables, and float variables.

·         Integers, as was mentioned, are whole numbers. They can't store the point something, like .7, .42, and .007. If you need to store numbers that are not whole numbers, you need a different type of variable. You can use the double type, or the float type. You set these types of variables up in exactly the same way: instead of using the word int, you type double, or float. Like this:

·         float myFloat;
double myDouble;

·         (Float is short for "floating point", and just means a number with a point something on the end.)

·         The difference between the two is in the size of the numbers that they can hold. For float, you can have up to 7 digits in your number. For doubles, you can have up to 16 digits. To be more precise, here's the official size:

·         float: 1.5 × 10-45 to 3.4 × 1038
double: 5.0 × 10-324 to 1.7 × 10308

·         Float is a 32-bit number and double is a 64-bit number.

·         To get some practice using floats and doubles, return to your form. If you can't see the Form1.cs [Design] tab at the top, right click Form1.cs in the Solution Explorer on the right hand side. (If you can't see the Solution Explorer, click View > Solution Explorer from the menu bar at the top.)

·        

·         Add a new button to your form. Set the following properties for it in the Properties Window:

·         Name btnFloat
Location: 110, 75
Text: Float

·         Double click your new button, and add the following line to the button code:

·         float myFloat;

·         Your coding window will then look like this:

·        

·         To store something inside of your new variable, add the following line:

·         myFloat = 0.42F;

·         The capital letter F on the end means Float. You can leave it off, but C# then treats it like a double. Because you've set the variable up as a float, you'll get errors if you try to assign a double to a float variable.

·         Add a third line of code to display your floating point number in a message box:

·         MessageBox.Show( myFloat.ToString( ) );

·         Again, we have to use ToString( ) in order to convert the number to a string of text, so that the message box can display it.

·         But your coding window should look like ours below:

·        

·         Run your programme and click your Float button. You should see a form like this:

·        

·         Halt the programme and return to your coding window. Now delete the capital letter F from 0.42. The line will then be:

·         myFloat = 0.42;

·         Try to run your programme again. You'll get an error message, and a blue wiggly line under your code. Because you've missed the F out, C# has defaulted to using a double value for your number. A float variable can't hold a double value, confirming that C# is a strongly typed language. (The opposite is a weakly typed language. PHP, and JavaScript are examples of weakly typed languages - you can store any kind of values in the variables you set up.)

·         Another thing to be careful of when using float variables is rounding up or down. As an example, change the number from 0.42F to 1234.567F. Now run your programme, and click your float button. The message box will be this:

·        

·         Halt the programme and return to your code. Now add an 8 before the F and after the 7, so that your line of code reads:

·         myFloat = 1234.5678F;

·         Now run your programme again. When you click the button, your message box will be this:

·        

·         It's missed the 7 out! The reason for this is that float variables can only hold 7 numbers in total. If there's more than this, C# will round up or down. A number that ends in 5 or more will be rounded up. A number ends in 5 or less will be rounded down:

·         1234.5678 (eight numbers ending in 8 - round up)
1234.5674 (eight numbers ending in 4 - round down)

·         The number of digits that a variable can hold is known as precision. For float variable, C# is precise to 7 digits: anything more and the number is rounded off.

·         In the next part, we'll take a closer look at doubles

·         Integers, as was mentioned, are whole numbers. They can't store the point something, like .7, .42, and .007. If you need to store numbers that are not whole numbers, you need a different type of variable. You can use the double type, or the float type. You set these types of variables up in exactly the same way: instead of using the word int, you type double, or float. Like this:

·         float myFloat;
double myDouble;

·         (Float is short for "floating point", and just means a number with a point something on the end.)

·         The difference between the two is in the size of the numbers that they can hold. For float, you can have up to 7 digits in your number. For doubles, you can have up to 16 digits. To be more precise, here's the official size:

·         float: 1.5 × 10-45 to 3.4 × 1038 
double: 5.0 × 10-324 to 1.7 × 10308

·         Float is a 32-bit number and double is a 64-bit number.

·         To get some practice using floats and doubles, return to your form. If you can't see the Form1.cs [Design] tab at the top, right click Form1.cs in the Solution Explorer on the right hand side. (If you can't see the Solution Explorer, click View > Solution Explorer from the menu bar at the top.)

·        

·         Add a new button to your form. Set the following properties for it in the Properties Window:

·         Name btnFloat
Location: 110, 75
Text: Float

·         Double click your new button, and add the following line to the button code:

·         float myFloat;

·         Your coding window will then look like this:

·        

·         To store something inside of your new variable, add the following line:

·         myFloat = 0.42F;

·         The capital letter F on the end means Float. You can leave it off, but C# then treats it like a double. Because you've set the variable up as a float, you'll get errors if you try to assign a double to a float variable.

·         Add a third line of code to display your floating point number in a message box:

·         MessageBox.Show( myFloat.ToString( ) );

·         Again, we have to use ToString( ) in order to convert the number to a string of text, so that the message box can display it.

·         But your coding window should look like ours below:

·        

·         Run your programme and click your Float button. You should see a form like this:

·        

·         Halt the programme and return to your coding window. Now delete the capital letter F from 0.42. The line will then be:

·         myFloat = 0.42;

·         Try to run your programme again. You'll get an error message, and a blue wiggly line under your code. Because you've missed the F out, C# has defaulted to using a double value for your number. A float variable can't hold a double value, confirming that C# is a strongly typed language. (The opposite is a weakly typed language. PHP, and JavaScript are examples of weakly typed languages - you can store any kind of values in the variables you set up.)

·         Another thing to be careful of when using float variables is rounding up or down. As an example, change the number from 0.42F to 1234.567F. Now run your programme, and click your float button. The message box will be this:

·        

·         Halt the programme and return to your code. Now add an 8 before the F and after the 7, so that your line of code reads:

·         myFloat = 1234.5678F;

·         Now run your programme again. When you click the button, your message box will be this:

·        

·         It's missed the 7 out! The reason for this is that float variables can only hold 7 numbers in total. If there's more than this, C# will round up or down. A number that ends in 5 or more will be rounded up. A number ends in 5 or less will be rounded down:

·         1234.5678 (eight numbers ending in 8 - round up)
1234.5674 (eight numbers ending in 4 - round down)

·         The number of digits that a variable can hold is known as precision. For float variable, C# is precise to 7 digits: anything more and the number is rounded off.

·         In the next part, we'll take a closer look at doubles

·         Add another button to your form, and set the following properties for it in the Properties Window:

·         Name: btnDouble
Location: 110, 130
Text: Double

·         Double click your new button to get at the code. Add the following three lines to your button code:

·         double myDouble;

·         myDouble = 0.007;

·         MessageBox.Show(myDouble.ToString());

·         Your coding window should now look like this:

·        

·         Run your programme and click your new button. You should see this:

·        

·         You also need to be careful of precision when using double variable types. The double type can hold up to 16 digits.

·         Halt your programme and return to the coding window. Change this line:

·         myDouble = 0.007;

·         to this:

·         myDouble = 12345678.1234567;

·         Run your programme and click your double button. The message box correctly displays the number. Add another number on the end, though, and C# will again round up or down. The moral is, if you want accuracy, careful of rounding!

·         In the next part, you'll see how to add up in C#.

·         We'll now use variables to do some adding up. After you have learned how to add up with the three number variable types, we can move on to subtraction, multiplication, and division.

·         Start a new project for this. So click File > Close Solution from the menu bar at the top of Visual C#. Then click File > New Project. Type arithmetic as the Name of your new Windows Forms Application project.Click OK to create the new project.

·         Add a button to your new form, and set the following properties for it in the Properties Window:

·         Name: btnAdd
Size: 100, 30
Text: Integer - Add

·         Move the button to the top of your form. Then double click it to get at the coding window. Set up the following three integer variables in your button code:

·         int firstNumber;
int secondNumber;
int integerAnswer;

·         Your coding window should look like ours below:

·        

·         We now need to put something into these variables. We'll store 10 in the first number, and 32 in the second number. So add these two lines to your code:

·         firstNumber = 10;
secondNumber = 32;

·         Your coding window will then look like this:

·        

·         So the numbers we want to store in the variables go on the right hand side of the equals sign; the variable names go on the left hand side of the equals sign. This assigns the numbers to the variables - puts them into storage.

·         We now want to add the first number to the second number. The result will be stored in the variable we've called integerAnswer. Fortunately, C# uses the plus symbol (+) to add up. So it's fairly simple. Add this line to your code:

·         integerAnswer = firstNumber + secondNumber;

·         And here's the coding window:

·        

·         We've already stored the number 10 in the variable called firstNumber. We've stored 32 in the variable secondNumber. So we can use the variable names to add up. The two variables are separated by the plus symbol. This is enough to tell C# to add up the values in the two variables. The result of the addition then gets stored to the left of the equals sign, in the variable calledintegerAnswer. Think of it like this:

·        

·         Calculate this sum first

·          

·        

·         Store the answer here

·          

·         To see if all this works or not, add a message box as the final line of code:

·         MessageBox.Show( integerAnswer.ToString( ) );

·         We're just placing the integerAnswer variable between the round brackets of Show( ). Because it's a number, we've had to use ToString( ) to convert the number to text. Here's what your coding window should look like now:

·        

·         And here's the form when the button is clicked:

·        

·         You don't have to store numbers in variables, if you want to calculate things. You can just add up the numbers themselves. Like this:

·         integerAnswer = 10 + 32;

·         And even this:

·         integerAnswer = firstNumber + 32;

·         So you can add up just using numbers, or you can mix variable names with numbers. As long as C# knows that there's a number in your variable, and that it's the right type, the addition will work.

·         You can use more than two variables, or more than two numbers. So you can do this:

·         integerAnswer = firstNumber + secondNumber + thirdNumber;

·         or this:

·         integerAnswer = firstNumber + secondNumber + 32;

·         And this:

·         integerAnswer = firstNumber + 10 + 32;

·         The results is the same: C# adds up whatever you have on the right hand side of the equals sign, and then stores the answer on the left hand side.

·         In the next part, you'll see how to add up with float variables.

Adding up with float Variables



You add up with float variables in exactly the same way - with the plus symbol. You can even mix integer variables with float variables. But you have to take care!

Add another button to your form, and set the following properties for it in the Properties Window:

Name: btnAddFloats
Size: 100, 30
Text: Float - Add

Double click your button to get at the code. Set up the following variables:

float firstNumber;
float secondNumber;
float floatAnswer;

And here's the coding window:


(Notice that we've used the same names for the first two variables. C# doesn't get confused, because they are in between the curly brackets of the button code. You can set up variables outside of the curly brackets. We'll do this when we come to code the calculator, at the end of this section. Then something called scope comes in to play. Don't worry about it, for now.)

To place something in your new variables, add the following code:

firstNumber = 10.5F;
secondNumber = 32.5F;

floatAnswer = firstNumber + secondNumber;

Finally, add you message box line:

MessageBox.Show( floatAnswer.ToString( ) );

The coding window should look like this:


Run your form and click your new button. You should see this:


So 10.5 + 32.5 equals 43. Halt your form by clicking the red X, and return to your coding window.

As was mentioned, you can add float and integer values together. But you need to take care. Try this:

Add the following variable to your code:

int integerAnswer;

And then change this line:

floatAnswer = firstNumber + secondNumber;

To this:

integerAnswer = firstNumber + secondNumber;

So it's just the name of the variable before the equals sign that needs to be changed.

Amend you message box line from this:

MessageBox.Show( floatAnswer.ToString( ) );

To this:

MessageBox.Show( integerAnswer.ToString() );

Your coding window will then look like this:


Try to run your code. The programme won't execute, and you'll have a blue wiggly line:


Hold your mouse over the blue wiggly line and you'll see an explanation of the error:


Not much help, if you're a beginner! But what it's telling you is that the first number and the second number are float variables. The answer to the addition was also a float. However, you were trying to store the answer in an integer variable. C# won't let you store float values in an integer. The error message is saying that you need to convert them first.

You can indeed convert float values to integers. You do it like this:

integerAnswer = (int) firstNumber + (int) secondNumber;

So you type the word int between a pair of round brackets. This goes before the number you want to convert. It does mean that the point something on the end will get chopped off, though. So 10.5 becomes 10, and 32.5 becomes 32. Not good for accuracy, but at least the programme will run!

Try it out, and you should see an answer of 42 when you click your button.

So the moral is this: If you're expecting an answer that ends in point something, use a float variable (or a double).

(You may have a green wiggly line under float floatAnswer. This is because you're not storing anything in this variable. Don't worry about it!)

Note that the other way round is not a problem - you can store an integer in a float value. Have a look at this slight change to the code:


First, notice the new way we are storing the number 20 into the integer variable calledintegerAnswer:

int integerAnswer = 20;

Instead of two lines, we've just used one. This is fine, in C#. But you're doing two things on the same line: setting up the variable, and placing a value in it.

The second thing to notice is that we are adding up two float values (firstNumber and secondNumber) and an integer (integerAnswer). We're then storing the answer into a float variable (floatAnswer). Try it out and you'll find that the code runs fine.

If we change this line:

firstNumber = 10.5F;

to this:

firstNumber = 10;

then, again, the programme will run fine. In other words, you can store an integer in a float variable, but you can't store a float value in an integer variable without converting.

Hopefully, that wasn't too confusing!

We'll move on to subtraction, now. But if you want to use a double variable instead of a float variable the same things apply - be careful of what you are trying to store, and where!

Getting Numbers from Text Boxes



We're going to change tack slightly, here. What we'll do is show you how to get numbers from text boxes, and then use these numbers in your code. You'll need to be able to do this for your calculator project, which is coming up soon!

Start a new project for this one by clicking File > New Project from the menu bar at the top of Visual C#.

Add a text box and a button to your new form. Set the following Properties for the text box (the tb below stands for text box):

Name: tbFirstNumber
Size: 50, 20
Location: 40, 35
Text: 10

And set the following properties for your button:

Name: btnAnswer
Size: 75, 25
Location: 90, 90
Text: Answer

Your form will then look like this:


What we want to do is to get that number 10 from the text box and display it in a message box.

So double click your button to get at the coding window. Your cursor will be flashing inside of the button code. Set up two integer variables at the top of the button code:

int firstTextBoxNumber;
int answer;

Your coding window should look like this:


To get at the number in the text box, we can use the Text property of text boxes. Here's the line of code to add:

firstTextBoxNumber = tbFirstNumber.Text;

This says, find a text box called tbFirstNumber. Access its Text property. When the Text property is retrieved, store it in the variable called firstTextBoxNumber.

To display the number in a message box, add this line:

MessageBox.Show( firstTextBoxNumber.ToString( ) );

Try to Run your code. You should find C# won't run it at all. It will give you the following error:


With text boxes, the thing that you get is, not surprisingly, text. However, we're trying to store the text from the text box into an integer variable. C# won't let you do this - whole numbers belong in integer variables, not text. The error message is telling you that C# can't do the conversion from text to numbers for you - you have to do it yourself!

So we need to convert the text from the text box into an integer. The way you do this is to use something called Parsing. Fortunately, this involves nothing more complex that typing the word "Parse". You can do different types of Parses. Because we need to convert the text into an integer, we need an Integer Parse. So change the line to this:

firstTextBoxNumber = int.Parse( tbFirstNumber.Text );

So you type int, then a full stop. From the IntelliSense menu, you can double click Parse. In between a pair of round brackets, you type the text you want to convert. In our case, the text is coming from a text box. But it doesn't have to. You can do this:

firstTextBoxNumber = int.Parse( "10" );

In the code above, the number is in double quotes. Double quotes mean that it is text. Usingint.Parse( ) means that it will be converted to a number that you can store in an integer variable.

Run your programme and you'll find that it works OK now. (You'll have a green wiggly line underanswer, but that's just because we haven't used this variable yet.) Click your button and the number 10 will appear in the message box. Type a different number in your text box, and click the button again. The new number should appear in place of the old one.

You can also Parse other types of variable. Like this:

float firstTextBoxNumber;
firstTextBoxNumber = float.Parse( tbFirstNumber.Text );

Or this:

double firstTextBoxNumber
firstTextBoxNumber = double.Parse( tbFirstNumber.Text );

In the first one, we've set up a float variable. We've then used float.Parse( ) to convert the text from the text box, so that it can be stored in the float variable. We've done exactly the same thing in the second example, to convert the text into a double.

Things get more complicated if you accidentally try to store a double value in a float variable - your programme will crash! You need to try to catch things like this with code. (You'll see how to test for errors like this later in the book.)

For now, let's move on.

OK, so we've got text from a text box and displayed it in a message box. What we'll do now is to add a second text box, get numbers from both, use our Math operators, and do some calculations with the two number we took from the text boxes. Sounds complex, but it isn't!

Add a second text box to your form. Set the following Properties for it in the Properties Window:

Name: tbSecondNumber
Size: 50, 20
Location: 165, 35
Text: 5

Your form will then look like this:


Double click the button to get at your code. Now set up another integer variable to hold the second number from the new text box:

int secondTextBoxNumber;

To store the number from the text box in this new variable, add the following line:

secondTextBoxNumber = int.Parse( tbSecondNumber.Text );

This is the same as before - use int.Parse to convert the number from the text box into an integer variable. Then store the number in the new variable.

Let's add the two numbers up, first. We can use the answer variable for this. Here's the code to add:

answer = firstTextBoxNumber + secondTextBoxNumber;

So we're just using the plus symbol ( + ) to add up whatever is in the two variables. The numbers in the variables come from the two text boxes.

Amend your message box line to this:

MessageBox.Show( answer.ToString( ) );

All you need to do is to change the name of the variable that your are converting ToString( ).

Your coding window should look like ours:


Run your programme, and then click the button. You should the answer to the addition in your message box:


Change the numbers in the text boxes, and click your button again. When you've finished playing with your new form, click the red X to return to the code. Here are a few exercises for you to try.

 

Exercise
Use the textboxes on your form to calculate the following (you'll need to amend your code for three of them):


1845 + 2858
3450 - 285
35 * 85
5656 / 7

(The answers you should get are: 4703, 3165, 2975 and 808.)

 

Exercise
Add a new text box to you form. Set up an integer variable to store a third number. Get the third number from the text box and calculate the following:


(1845 + 2858) - 356
(3450 - 285) * 12
35 * ( 85 - 8 )
(5656 / 7) + 2156

(The answers you should get are: 4347, 37980, 2695 and 2964. You'll have to keep closing the form down. Then add round brackets, the operator symbols, and the new variable.)


Once you've completed the exercises, you can move on to tackling the next project - your very own calculator


A C# .NET Calculator - Design Stage


You're now going to write your own very own C# .NET calculator programme. We'll keep it simple at first, and the only thing it will be able to do is add up. After you understand how it all works, we'll make it divide, subtract and multiply. Version 1 of your calculator will look like this:


As you can see, it has a text box for the display of numbers, buttons for the numbers 0 to 9, a point symbol, plus and equals buttons, and a clear button.

So the first thing to do is to design your calculator. Start a new project by clicking File > New project. For your new form, set the following properties:

Size: 440, 487
Text: Calculator

To add a bit of colour to your calculator, you can change the BackColour property of the form, as in the image below:


We went for an orange colour, but feel free to choose any colour you like.

Now add a text box to your form and set the following properties for it:

Name: txtDisplay
Location: 66, 52
Size: 200, 26
TextAlign: Right

Time to add the buttons. You need 10 buttons for the numbers 0 to 9. Add the first button to the form, and set the following properties for it:

Name: btnZero
Font: Microsoft Sans Serif, Bold, 12
Location: 143, 378
Size: 49, 40
Text: 0

This is the zero button, which goes at the bottom. Add a new button to your form and set the following properties for it:

Name: btnOne
Font: Microsoft Sans Serif, Bold, 12
Location: 66, 159
Size: 49, 40
Text: 1

An easier way to add new buttons, is to copy and paste them. Click on btnOne to select it. Right click the button and select Copy from the menu that appears. Now click anywhere on the form. Right click again, and select Paste. A new button will appear with the number 1 on it. Have a look at the properties window, though, and you'll see that the new button has the Name button1. Change it tobtnTwo. Then change the Text property to 2. Drag it in to position next to your number 1 button.

Add the other number buttons in the same: Copy, Paste, change the Name and the Text properties. For the other number buttons, use the following for the Name properties: btnThree, btnFour, btnFive, etc. Position your buttons like ours.

Add a new button for the Point symbol. Give it the Name btnPoint, and type a full stop (period) for the Text property. Change the Font property, if you think it's too small.

Only three buttons to go. So add three more buttons, and use the following properties:

Name: btnPlus
Font: Microsoft Sans Serif, Bold, 12
Location: 324, 159
Size: 49, 40
Text: +

Name: btnEquals
Font: Microsoft Sans Serif, Bold, 12
Location: 324, 230
Size: 49, 40
Text: =

Name: btnClear
Font: Microsoft Sans Serif, Bold, 8
Location: 324, 305
Size: 49, 40
Text: Clear

Change the locations, though, if they don't match the alignment for your own buttons. But you've now completed the design of your calculator. Save your hard work, and we can begin the coding in the next part.

C# .NET Calculator - The Code



Before we get to the code, let's just go through how our calculator is going to work:

  1. Click the number buttons. This will be the first number in the addition
  2. The first number you want to add will then appear in the text box
  3. Click the Plus button to tell the calculator you want to add
  4. The first number will disappear from the text box, ready for the second number
  5. Click the number buttons again to add the second number
  6. Click the equals button and the answer appears in the text box

The first task on the list is to get the number to appear in the text box when a number button is clicked. To do this, double click your number 1 button to get at the code.

The numbers on the buttons were put there by changing the Text property. So the only thing we need to do is to access this Text property. We can then use the button text as the text Property for the text box. Add the following line for your btnOne code:

txtDisplay.Text = btnOne.Text;

This says, "Make the Text in the text box the same as the Text that's on the button". Remember: whatever is on the right of the equals sign gets stored in whatever is on the left of the equals sign.

Run your programme and try it out. Click the number 1 button and it will appear in your text box. Click your number 1 a few times and what do you notice? You might think that clicking the number 1 button twice, for example, will cause the text box to display 11, and not 1. After all, you clicked it twice, so why shouldn't two number 1's appear?

The reason it doesn't is because you haven't told C# to keep the value that was already there. Each time you click the button, C# is starting afresh - it doesn't know what was in there before, and discards the number that you previously stored.

Halt your programme and return to your code. Change your line to this:

txtDisplay.Text = txtDisplay.Text + btnOne.Text;

This line is easier to read if you just look at the part after the equals sign. Which is this:

txtDisplay.Text + btnOne.Text;

When you're working with text, the plus symbol doesn't mean add - it means concatenate (you learned about this in the previous section when working strings). So C# will join the text in the text box with the text on the button. After it has finished doing this, it will store the answer to whatever is on the left of the equals sign. In this case, it's not a variable but the text property of the text box.

Run your programme again. Click the number one button a few times. You should find that the number one will appear in the text box more than once.

Halt the programme and return not to your code but to the form itself. (If you can't see your form, right-click Form1.cs in the Solution Explorer on the right. From the menu that appears, select View Designer.)

Now double click button 2, and add the following code:

txtDisplay.Text = txtDisplay.Text + btnTwo.Text;

The only thing that's different is the name of the button - btnTwo instead of btnOne. The rest is the same.

Do the same for the rest of your button, changing the name of the button each time. (You can copy and paste your code to save time.)

But your coding window should look like this, when you've finished:


Run your programme again, and click all ten of your buttons. Make sure that each number appears in the text box when its button is clicked.

Return to your form and double click the Clear button. Add the following line:

txtDisplay.Clear( );

After the full stop, you type the word Clear, followed by a pair of round brackets. Clear is a method you can use on text boxes. As its name suggests, it will clear the text box, leaving it blank.

Run your programme again, click a few numbers, then try your Clear button. The numbers should disappear from the text box.

In the next part, we'll add the code for the Plus button.

C# Calculator - The Plus Button



So we've got the numbers to appear in the text box when a button is clicked. The next thing we need to do is grab that number and store it somewhere. We'll then use this number when the equals button is clicked. (The equals button will do the addition, not the plus button.)

The plus button, then, needs to grab the number from the text box. Because it's text, we need to convert it to a number. We'll then store that number in a variable. The only other line of code we'll need for the Plus button is to clear the text box, ready for the second number.

The first number needs to be stored in a variable. We'll use the double type of variable. That way, we can have really big numbers with a "point something" at the end.

So that all the buttons in the programme can see this variable, it needs to be set outside of any button code. So we can't do this:

private void btnOne_Click(object sender, EventArgs e)
{

double total1 = 0;

}

If you set up a variable inside of a button only this button will be able to do anything with the variable. This is known as scope. Because we've set up the variable inside of the button code, we've given it local scope: it can only be seen inside of the curly brackets. To make the variable accessible to all the buttons, we need to give it what's knows as global scope. This is fairly easy - just set it up outside of any buttons. Like this:

double total1 = 0;

private void btnPlus_Click(object sender, EventArgs e)
{

}

Now the variable is outside of the curly brackets, making it available to all the buttons on our form. So set up that variable in your own code.

For the btnPlus code itself, add the following two lines (in blue bold below):

double total1 = 0;

private void btnPlus_Click(object sender, EventArgs e)
{

total1 = total1 + double.Parse( txtDisplay.Text );
txtDisplay.Clear();

}

All we're doing here is getting the text from the text box, converting it to a double number, and then storing it in the total1 variable. Notice that we've also done this:

total1 = total1 +

Just like we did for the number buttons, we need to keep whatever was in the total1 variable. You need to do this in case you want to add more than two numbers. If you didn't keep what was in the total1 variable, C# would "forget" what was in it, and start afresh. This technique is so common in programming that a shorthand way of doing this is usually implemented:

total1 += double.Parse(txtDisplay.Text);

So instead of repeating the variable name, you just use a plus symbol and an equals symbol together ( += ). The above line does exactly the same thing as this:

total1 = total1 + double.Parse(txtDisplay.Text);

But whichever way you choose to retain a value in a variable, all you're saying is "Keep whatever is already in the variable, and add something else".

After storing the number from the text box, we need to clear it:

txtDisplay.Clear( );

Once the text box is cleared, a second number can be selected by clicking the number buttons.

In the next part, you'll learn how to code for the Equals button.

C# Calculator - The Equals Button



The Equals button is where the action takes place. This is where we will do the actual addition.

To store the answer to the addition, we'll need another variable (in blue bold below):

double total1 = 0;

double total2 = 0;

private void btnPlus_Click(object sender, EventArgs e)
{

total1 = total1 + double.Parse(txtDisplay.Text);
txtDisplay.Clear();

}

So set up a total2 variable in your code, as we've done above.

Return to your Form, and double click the Equals button to get at your code. Now add the following three lines of code:

total2 = total1 + double.Parse( txtDisplay.Text );
txtDisplay.Text = total2.ToString( );
total1 = 0;

The first line should look familiar:

total2 = total1 + double.Parse( txtDisplay.Text );

To the right of the equals sign, we're doing the same thing as before:

total1 + double.Parse(txtDisplay.Text);

The difference is before the equals sign: we're now storing it in the total2 variable:

total2 = total1 + double.Parse(txtDisplay.Text);

In other words, get the number from the text box, convert it to a double variable, add it to whatever is in total1. When all this is worked out, store the answer in the variable called total2.

The second line of code was this:

txtDisplay.Text = total2.ToString( );

On the right of the equals sign, we're converting the total2 variable To a String. This is so that it can be displayed as Text in the text box.

The third line of code resets the total1 variable to zero:

total1 = 0;

This is so a new sum can be calculated.

Time to try out your calculator. Use it to calculate the following:

10 + 25
36 + 36
10 + 10 + 10

Of course, you can do these sums in your head. But make sure that your calculator gets its sums right before going any further. Click your Clear button to start a new addition. When you're sure you understand what is going on with the code, try this exercise.

Exercise C
You have not yet written any code for the btnPoint button. This means that you can't have numbers like 10.5 or 36.7 in your additions. Write code to solve this. (Hint: you only need one line of code.)


Conditional Logicin C# .NET


 

 

Conditional Logic is all about the IF word. In fact, it's practically impossible to programme effectively without using IF. You can write simple programmes like our calculator. But for anything more complicated, you need to get the hang of Conditional Logic.

As an example, take the calculator programme you have just written. It only has a Plus button. We'll be adding another button soon, a Subtract button. Now, you can't say beforehand which of the two buttons your users will click. Do they want to add, or subtract? You need to be able to write code that does the following:

IF the Plus button was clicked, add up
IF the Minus button was clicked, subtract

You can rearrange the two statements above.

Was the Plus button clicked? Yes, or No?
Was the Minus button clicked? Yes, or No?

So the answer for each is either going to be Yes, or No - the button is either clicked, or not clicked.

 

IF Statements


To test for YES or NO values, you can use an IF statement. You set them up like this:

if ( )
{

}

So you start with the word if (in lowercase), and type a pair of round brackets. In between the round brackets, your type what you want to check for (Was the button clicked?). After the round brackets, it's convenient (but not strictly necessary) to add a pair of curly brackets. In between your curly brackets, you type your code. Your code is what you want to happen IF the answer to your question was YES, or IF the answer was NO. Here's a coding example:

bool buttonClicked = true;

if (buttonClicked = = true)
{

MessageBox.Show(“The button was clicked”);

}

Notice the first line of code:

bool buttonClicked = true;

This is a variable type you haven't met before - bool. The bool is short for Boolean. You use a Boolean variable type when you want to check for true or false values (YES, or NO, if you prefer). This type of variable can only ever be true or false. The name of the bool variable above is buttonClicked. We've set the value to true.

The next few lines are our IF Statement:

if (buttonClicked == true)
{

MessageBox.Show(“The button was clicked”);

}

The double equals sign ( ==) is something else you need to get used to when using IF Statements. It means "Has a value of". The double equals sign is known as a Conditional Operator. (There are a few others that you'll meet shortly.) But the whole of the line reads:

"IF buttonClicked has a value of true"

If you miss out one of the equals signs, you'd have this:

if (buttonClicked = true)

What you're doing here is assigning a value of true to the variable buttonClicked. It's not checking if buttonClicked "Has a value of" true. The difference is important, and will cause you lots of problems if you get it wrong!

In between the curly brackets of the IF statement, we have a simple MessageBox line. But this line will only get executed IF buttonClicked has a value of true.

Let's try it out. Start a new project for this (File > New Project). Add a button to your new form, and set the Text property to "IF Statement". Double click the button, and add the code from above. So your coding window will look like this:


Run your programme and click the button. You should see the message box. Now halt the programme and change this line:

bool buttonClicked = true;

to this

bool buttonClicked = false;

So the only change is from true to false. Run your programme again, and click the button. What happens? Nothing!

The reason that nothing happens is that our IF Statement is checking for a value of true:

if (buttonClicked == true)

C# will only execute the code between the curly brackets IF, and only IF, buttonClicked has a value of true. Since you changed the value to false, it doesn't bother with the MessageBox in between the curly brackets, but moves on instead.

 

Else


You can also say what should happen if the answer was false. All you need to do is make use of theelse word. You do it like this:

if (buttonClicked = = true)
{

}
else
{

}

So you just type the word else after the curly brackets of the IF Statement. And then add another pair of curly brackets. You then write your code for what should happen if the IF Statement was false. Change your code to this:

if (buttonClicked = = true)
{

MessageBox.Show("buttonClicked has a value of true");

}
else
{

MessageBox.Show("buttonClicked has a value of false");

}

So the whole thing reads:

"IF it's true that buttonClicked has a value of true, do one thing. If it's not true, do another thing."

Run your programme, and click the button. You should see the second MessageBox display. Halt the programme and change the first line back to true. So this:

bool buttonClicked = true;

instead of this:

bool buttonClicked = false;

Run the programme again, and click the button. This time, the first message box will display.

The whole point of using IF ..Else Statements, though, is to execute one piece of code instead of some other piece of code.

You can also extend the IF statement and add an else ... if part. This will be useful in our calculator programme. Click below to continue the lessons.

Else ... If statements in C# .NET



 


Instead of using just the else word, you can use else if, instead. If we use our calculator as an example, we'd want to do this:

bool plusButtonClicked = true;
bool minusButtonClicked = false;

if (plusButtonClicked = = true)
{

//WRITE CODE TO ADD UP HERE

}
else if (minusButtonClicked = = true)
{

//WRITE CODE TO SUBTRACT HERE

}

So the code checks to see which button was clicked. If it's the Plus Button, then the first IF Statement gets executed. If it's the Minus Button, then the second IF Statement gets executed.

But else if is just the same as if, but with the word else at the start.

In fact, we can now add a minus button to our calculator. We'll use else if.

So open up your calculator project again. To do this, click the link on the Start Page Tab in Visual C#. If you can't see your Start Page tab, click its icon at the top of the C# software:


(In version 2012, click View > Start Page from the menu at the top.)

You should then see a section headed Recent Projects:


Look for your calculator project here. You can also click File > Recent Projects from the menu bar at the top.

If both of those fail, click File > Open Project. Navigate to where you saved your project. Open up the file that ends in .sln.

With your calculator project open, add a new button. Set the following properties for it in the Properties Window:

Name: btnMinus
Font: Microsoft Sans Serif, 16, Bold
Location: Move it to the right of your Plus button
Size: 49, 40
Text: -

Now double click your Minus button to get at its code. Add the following two Boolean variables outside of the Minus button code, just above it:

bool plusButtonClicked = false;
bool minusButtonClicked = false;

You coding window will then look like this:


Now add the following code inside of the Minus button:

total1 = total1 + double.Parse(txtDisplay.Text);
txtDisplay.Clear( );

plusButtonClicked = false;
minusButtonClicked = true;

Your coding window will then look like the one below:


All we've done here is to set up two Boolean variables. We've set them both to false outside of the code. (They have been set up outside of the code because other buttons need to be able to use them; they have been set to false because no button has been clicked yet.) When the Minus button is clicked, we'll set the Boolean variable minusButtonClicked to true and the plusButtonClicked to false.

But the first two lines are exactly the same as for the Plus button:

total1 = total1 + double.Parse(txtDisplay.Text);
txtDisplay.Clear( );

The first line just moves the numbers from the text box into the total1 variable. The second line clears the text box.

Now access the code for your Plus button. Add two lines of code to the end:


So the only thing you are adding is this:

plusButtonClicked = true;
minusButtonClicked = false;

The Plus button resets the Boolean variables. This time, plusButtonClicked gets set to true, andminusButtonClicked gets set to false. It was the other way round for the Minus button.

The reason we're resetting these Booleans variables is because we can use them in an if elsestatement. We can add up if the plusButtonClicked variable is true, and subtract ifminusButtonClicked is true.

We'll still do the calculating in the Equals button. So change your equals button to this:


We're using Conditional Logic to decide which of the two buttons was clicked. The first IF statement checks if the plusButtonClicked variable is true. If it is, then the addition gets done (this is exactly the same as before). If the first IF Statement is false, then C# moves down to the else if statement. IfminusButtonClicked is true, then the subtraction gets done instead. The only difference between the addition and subtraction lines is the Operator symbols: a plus (+) instead of a minus (-).

The final two lines of code are the same as before - convert the number to text and display it in the text box, and then reset the total1 variable to zero.

Run your calculator and try it out. You should be able to add and subtract!

 

Exercise D
Finish your calculator by adding Divide and Multiply buttons to your form. Write the code to make your calculator Divide and Multiply.


For this exercise, you're just adding two more Boolean variables to your code. You can then add more else if statements below the ones you already have. You'll also need to add two more lines to the code for your four Operator buttons. These two lines need to reset the Boolean variables to either true or false. For example, here's the code for the Minus button to get your started:


So we now have four Boolean variables outside the button code, one for the plus button, one for minus button, one for divide button, and one for the multiply button. When you click a button, its Boolean variable gets set to true.

Do the same for the other three buttons. Then write your else if statements. This is quite a tricky exercise, though. Probably your hardest so far!

Switch Statements in C# .NET



 


An easier way to code the calculator is by using a switch statement instead of an else if statement. A switch statement allows you to check which of more than one option is true. It's like a list of if statements. The structure of a switch statement looks like this:


After the word switch, you type a pair of round brackets. In between the round brackets, you type what you want to check for. You are usually testing what is inside of a variable. Then type a pair of curly brackets. In between the curly brackets, you have one case for each possible thing that your variable can contain. You then type the code that you want to execute, if that particular case is true. After your code, type the word break. This enables C# to break out of the Switch Statement altogether.

We'll use our calculator as a coding example.

Our four buttons set a Boolean variable to either true or false. Instead of doing this, we could have the buttons put a symbol into a string variable. Like this:

string theOperator;

private void btnPlus_Click(object sender, EventArgs e)
{

total1 = total1 + double.Parse(txtDisplay.Text);
txtDisplay.Clear();

theOperator = "+";

}

So the last line of code puts the + symbol into a string variable we've called theOperator. It will only do this if the button is clicked. The other buttons can do the same. We can then use a switch statement in our Equals button to check what is in the variable we've called theOperator. This will tell us which button was clicked. Here's the code that would go in the Equals button.


In between the round brackets after the word switch, we've typed the name of our variable (theOperator). We want to check what is inside of this variable. It will be one of four options: +, -, *, /. So after the first case, we type a plus symbol. It's in between double quotes because it's text. You end a case line with a colon:

case "+" :

The code to add up goes on a new line. After the code, the break word is used. So what you're saying is:

"If it's the case that theOperator holds a + symbol, then execute some code"

We have three more case parts to the switch statement, one for each of the math symbols. Notice the addition of this, though:

default :

//DEFAULT CODE HERE
break;

You use default instead case just "in case" none of the options you've thought of are what is inside of your variable. You do this so that your programme won't crash!

 

C# Operators



 


You've already met one Conditional Operator, the double equals sign ( == ). You use this in IF Statement when you want to check if a variable "has a value of" something:

if ( myVariable == 10) 
{

//EXECUTE SOME CODE HERE

}

So the above line reads, "IF whatever is inside of myVariable has a value of 10, execute some code."

Other Conditional Operators you'll use when you're coding are these:


Because you need to learn these Operators, let's get some practice with them.

Start a new project. Add two text boxes and a button to your form. Resize the text boxes and type 8 as the Text property for the first text box, and 7 as the Text property for the second text box. Set the Text property for the button to the word "Compare". Your form will then look like this:


Double click the button to get at the coding window. What we'll do is to get the numbers from the text boxes and test and compare them. So the first thing to do is to set up some variables:

int firstNumber;
int secondNumber;

Then get the text from the text boxes and store them in the variables (after converting them to integers first.)

firstNumber = int.Parse(textBox1.Text);
secondNumber = int.Parse(textBox2.Text);

What we want to do now is to compare the two numbers. Is the first number bigger than the second number? To answer this, we can use an IF Statement, along with one of our new Conditional Operators. So add this to your code:

if (firstNumber > secondNumber)
{

MessageBox.Show("The first number was greater than the second number");

}

Your coding window will then look like this (our message box above is only on two lines because it can't all fit on this page):


So in between the round brackets after if, we have our two variables. We're then comparing the two and checking to see if one is Greater Than ( > ) the other. If firstNumber is Greater ThansecondNumber then the message box will display.

Run your programme and click your button. You should see the message box display. Type a 6 in the first text box, and click the button again. The message box won't display. It won't display because 6 is not greater than 7. The message box code is inside of the curly brackets of the IF Statement. And the IF Statement only gets executed if firstNumber is Greater Than secondNumber. If it's not, C# will just move on to the next line. You haven't got any more lines, so C# is finished.

Stop your programme and go back to your code. Add a new if statement below your first one:

if (firstNumber < secondNumber)
{

MessageBox.Show("The first number was less than the second number");

}

Again, our message box above is spread over two lines because there's not enough room for it on this page. Your message box should go on one line. But the code is just about the same! The thing we've changed is to use the Less Than symbol ( < ) instead of the Greater Than symbol ( > ). We've also changed the text that the message box displays.

Run your programme, and type a 6 in the first text box. You should see your new message box display. Now type an 8 in the first text box, and click your button. The first message box will display. Can you see why? If your programme doesn't work at all, make sure it is like ours in the image below:


With your programme still running, type a 7 in the first box. You will then have a 7 in both text boxes. Before you click your button, can you guess what will happen?

The reason that nothing happens at all is because you haven't written any code to say what should happen if both numbers are equal. For that, try these new symbols:

>= (Greater Than or Equal to)

And these ones

<= (Less Than or Equal to)

Try these new Conditional Operators in place of the ones you already have. Change the text for your message boxes to suit. Run your code again. When you click the button, both message boxes will display, one after the other. Can you see why this happens?

Another Conditional Operator to try is Not Equal To ( != ). This is an exclamation mark followed by an equals sign. It is used like this:

if (firstNumber != secondNumber )
{

//SOME CODE HERE

}

So, "IF firstNumber is not equal to secondNumber execute some code."

You can even use the exclamation mark by itself. You do this when you want to test for a false value between the round brackets after if. It's mostly used with Boolean values. Here's an example:

bool testValue = false;

if (!testValue)
{

MessageBox.Show("Value was false");

}

So the exclamation mark goes before the Boolean value you want to test. It is a shorthand way of saying "If the Boolean value is false". You can write the line like this instead:

if (testValue == false)

But experienced programmers just use the exclamation mark instead. It's called the NOT Operator. Or the "IF NOT true" Operator.

Try not to worry if you don't have a thorough grasp of all the Conditional Operators yet - you'll get the hang of them as you go along. But try the next exercise.

 

Exercise F
Write a small programme with a text box and a button. Add a label to ask people to enter their age. Use Conditional Logic to test how old they are. Display the following messages, depending on how old they are:


Less than 16: "You're still a youngster."
Over 16 but under 25: "Fame beckons!"
Over 25 but under 40: "There's still time."
Over 40: "Oh dear, you've probably missed it!"

Only one message box should display, when you click the button. Here's some code to get you started:

int age;

age = int.Parse(textBox1.Text);

if (age < 17)
{

MessageBox.Show("Still a youngster.");

}

For the others, just add more IF Statements, and more Condition Operators.


 

AND and OR


The final two Operators we'll have a look at are these:

&& (And)
|| (Or)

These two are known as Logical Operators, rather than Conditional Operators (so is the NOT operator).

The two ampersand together (&&) mean AND. You use them like this:

bool isTrue = false;
bool isFalse = false;

if ( isTrue == false && isFalse == false )
{

}

You use the AND operator when you want to check more than one value at once. So in the line above, you're checking if both values are false. If and ONLY if both of your conditions are met will the code between curly brackets get executed. In the code above, we're saying this:

"If isTrue has a value of false AND if isFalse has a value of false then and only then executed the code between curly brackets."

If isTrue is indeed true, for example, then any code between curly brackets won't get executed - they both have to be false, in our code.

You can test for only one condition of two being met. In which, use the OR ( | | ) operator. The OR operators is two straight lines. These can be found above the back slash character on a British keyboard, which is just to the left of the letter "Z". (The | character is known as the pipe character.) You use them like this:

bool isTrue = false;
bool isFalse = false;

if ( isTrue == false || isFalse == false )
{

}

We're now saying this:

"If isTrue has a value of false OR if isFalse has a value of false then and only then executed the code between curly brackets."

If just one of our variables is false, then the code in between curly brackets will get executed.

If all that sounds a bit complicated, don't worry about it - you'll get more practice as we go along

 

In the next section, we'll have a look at loops, which are another crucial hurdle to overcome in programming. By the end of the section, you'll have written your own times table programme

C# and Loops



 

We've produced a video to go with this lesson. It's recommended that you read the text below as well, though. The video is here:


Loops are an important part of any programming language, and C# is no different. A loop is a way to execute a piece of code repeatedly. The idea is that you go round and round until an end condition is met. Only then is the loop broken. As an example, suppose you want to add up the numbers one to ten. You could do it like this:

int answer;
answer = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10;

And this would be OK if you only had 10 numbers. But suppose you had a thousand numbers, or ten thousand? You're certainly not going to want to type them all out! Instead, you use a loop to repeatedly add the numbers.

 

For Loops in C#


The first type of loop we'll explore is called a for loop. Other types are do loops and while loops, which you'll meet shortly. But the for loop is the most common type of loop you'll need. Let's use one to add up the numbers 1 to 100.

Start a new project by clicking File > New Project from the menu bars at the top of Visual Studio. Now add a button to the new form. Double click the button to get at the code. To quickly add a code stub for a loop, right click anywhere between the curly brackets of the button code. From the menu that appears, click on Insert Snippet:


When you click on Insert Snippet, you'll see a list of items:


Scroll down and double click on for. Some code is added for you:


It all looks a bit complicated, so we'll go through it. Here's the for loop without anything between the round brackets:

for ( ) 
{

}

So you start with the word for, followed by a pair of round brackets. What you are doing between the round brackets is telling C# how many times you want to go round the loop. After the round brackets, you type a pair of curly brackets. The code that you want to execute repeatedly goes between the curly brackets.

The default round-bracket code that C# inserts for you is this:

int i = 0; i < length; i++

There's three parts to the round-bracket code:

  1. Which number do you want to start at?
  2. How many times do you want to go round and round?
  3. How do you want to update each time round the loop?

Note that each of the three parts is separated by a semi-colon. Here's the first part:


And here's the second part:


And here's the third part:


Number 1 on the list above (Which number do you want to start at?) is this:

int i = 0;

What the default code is doing is setting up an integer variable called i (a popular name for loop variables.) It is then assigning a value of 0 to the i variable. It will use the value in i as the starting value of the loop. You can set up your starting variable outside the code, if you prefer. Like this:

int i

for (i = 0; i < length; i++) 
{

}

So the variable called i is now set up outside the loop. We then just need to assign a value to the variable for the first part of the loop.

Number 2 on the list above (How many times do you want to go round and round?) was this:

i < length;

This, if you remember your Conditional Logic from the previous section, says "i is less than length". But length is not a keyword. So you need to either set up a variable called length, or replace the word length with a number. So either this:

for (int i = 0; i < 101; i++)

Or this:

int length = 101;

for (int i = 0; i < length; i++)
{

}

In the first example, we've just typed the i < 101. In the second example, we've set up a variable called length, and stored 101 in it. We're then just comparing one variable to another, and checking that i is less than length:

i < length;

If i is less than length, then the end condition has NOT been met and C# will keep looping. In other words, "Keep going round and round while i is less than length."

But you don't need to call the variable length. It's just a variable name, so you can come up with your own. For example:

int endNumber = 101;

for (int i = 0; i < endNumber; i++)
{

}

Here, we've called the variable endNumber instead of length. The second part now says "Keep looping while i is less than endNumber".

Number 3 on the list above (How do you want to update each time round the loop? ) was this:

i++

This final part of a for loop is called the Update Expression. For the first two parts, you set a start value, and an end value for the loop. But C# doesn't know how to get from one number to the other. You have to tell it how to get there. By typing i++, you are adding 1 to the value inside of i each time round the loop. (called incrementing the variable). This:

variable_name++

is a shorthand way of saying this:

variable_name = variable_name + 1

All you are doing is adding 1 to whatever is already inside of the variable name. Since you're in a loop, C# will keep adding 1 to the value of i each time round the loop. It only stops adding 1 to i when the end condition has been reached (i is no longer less than length).

So to recap, you need a start value for the loop, how many times you want to go round and round, and how to get from one number to the other.

So your three parts are these:

for (Start_Value; End_Value; Update_Expression)

OK, time to put the theory into practice. Type the following for your button code:


The actual code for the loop, the code that goes inside of the curly brackets, is this:

answer = answer + i;

This is probably the trickiest part of loops - knowing what to put for your code! Just remember what you're trying to do: force C# to execute a piece of code a set number of times. We want to add up the numbers 1 to 100, and are using a variable called answer to store the answer to the addition. Because the value in i is increasing by one each time round the loop, we can use this value in the addition. Here are the values the first time round the loop:


The second time round the loop, the figures are these:


The third time round the loop:


And the fourth:


Notice how the value of i increases by one each time round the loop. If you first do the addition after the equals sign, the above will make more sense! (As an exercise, what is the value of answer the fifth time round the loop?)

Run your programme, and click the button. The message box should display an answer of 5050.

 

In the next part, we'll take a closer look at loop start values and loop end values.

Loop Start Values and Loop End Values



 


In the code from the previous page, we typed the start value and end value for the loop. You can also get these from text boxes.

Add two text boxes to your form. Add a couple of labels, as well. For the first label, type Loop Start. For the second label, type Loop End. Your form will then look something like this:


What we'll do is to get the start value and end value from the text boxes. We'll then use these in our for loop.

So double click your button to get at the code (or press F7 on your keyboard). Set up two variables to hold the numbers from the text boxes:

int loopStart;
int loopEnd;

Now store the numbers from the text boxes into the two new variables:

loopStart = int.Parse(textBox1.Text);
loopEnd = int.Parse(textBox2.Text);

Now that we have the numbers from the text boxes, we can use them in the for loop. Change you for loop to this:

for (int i = loopStart; i < loopEnd; i++)
{

answer = answer + i;

}

The only thing you're changing here is the part between the round brackets. The first part has now changed from this:

int i = 1

to this:

int i = loopStart

So instead of storing a value of 1 in the variable called i, we've stored whatever is in the variable called loopStart. Whatever you type in the first text box is now used as the starting value of the loop.

For the second part, we've changed this:

i < 101

to this:

i < loopEnd

We're using the value stored inside of loopEnd. We're telling C# to keep looping if the value inside of the i variable is less than loopEnd. (Remember, because our Update Expression is i++, C# will keep adding 1 to the value of i each time round the loop. When i is no longer less than loopEnd, C# will stop looping.)

Run your programme and type 1 in the first text box and 10 in the second text box. Click your button. You should find that the message box displays an answer of 45.

Can you see a problem here? If you wanted to add up the numbers from 1 to 10, then the answer is wrong! It should be 55, and not 45. Can you see why 45 is displayed in the message box, and not 55? If you can't, stop a moment and try to figure it out.

(There is, of course, another problem. If you don't type anything at all in the text boxes, your programme will crash! It does this because C# can't convert the number from the text box and store it in the variable. After all, you can't expect it to convert something that's not there! You'll see how to solve this at the end of the chapter.)

 

In the next lesson, we'll use this same Form to create a Times Table programme in C#

A Times Table Programme in C#



 


We can now write a little times table programme. We'll use the text boxes to ask users to input a start number and end number. We'll use these to display the 10 times table. So if the user types a 1 into the first text box and a 5 into the second text box, we'll display this:

1 times 10 = 10
2 times 10 = 20
3 times 10 = 30
4 times 10 = 40
5 times 10 = 50

Instead of using a message box to display the results, we'll use a List Box. A list box, you will not be surprised to hear, is used to display lists of items. But it's easier to show you what they do rather than explain. So use the Toolbox on the left of Visual C# to add a list box to your form:


Resize your list box, and your form will now look something like ours below:


Double click your button to get at your code. Now add this line to your loop (the line to add is in blue bold below):

for (int i = loopStart; i <= loopEnd; i++)
{

answer = answer + i;

listBox1.Items.Add( answer.ToString() );

}

So you start by typing the Name of your list box (listBox1, for us). After a dot, you should see the IntelliSense list appear. Select Items from the list. Items is another property of list boxes. It refers to the items in your list. After the word Items, you type another dot. From the IntelliSense list, select theAdd method. As its name suggests, the Add method adds items to your list box. Between the round brackets, you type what you want to add to the list of items. In our case, this was just the answer, converted to a string.

You can delete the message box line, if you like, because you don't need it. But run your programme and enter 1 in the first text box and 5 in the second text box. Click your button and your form should look like this:


The programme is supposed to add up the number 1 to 5, or whatever numbers were typed in the text boxes. The list box is displaying one answer for every time round the loop. However, it's only displaying 4 items. If you solved the problem as to why 45 was displayed in the message box, and not 55 then you'll already know why there are only four items in the list box. If you didn't, examine the first line of the for loop:

for (int i = loopStart; i < loopEnd; i++)

The problem is the second part of the loop code:

i < loopEnd

We're telling C# to go round and round while the value in i is less than the value in loopEnd. C# will stop looping when the values are equal. The value in loopEnd is 5 in our little programme. So we're saying this to C#, "Keep looping while the value in i is less than 5. Stop looping if it's 5 or more."

Cleary, we've used the wrong Conditional Operator. Instead of using the less than operator, we need … well, which one do we need? Replace the < symbol with the correct one.

 

Exercise G
For some extra points, can you think of another way to solve the problem? One where you can keep the less than symbol?



 

To add some more information in your list box, change your line of code to this:

listBox1.Items.Add( "answer = " + answer.ToString( ) );

The thing to add is the text in red above. We've typed some direct text "answer=" and followed this with the concatenation symbol ( + ). C# will then join the two together, and display the result in your list box. Run your programme again, and the list box will be this:


To make it even clearer, add some more text to your list box. Try this:

listBox1.Items.Add( "i = " + i + " answer = " + answer.ToString( ) );

Again, the text to add is in blue. Run your programme, and your list box will look like this:


We've now added the value of the variable called i. This makes it clear how the value of i changes each time round.

 

The Times Table Programme


We now have all the ingredients to write the Times Table programme.

So return to your coding window. What we're going to do, remember, is to use a for loop to calculate and display the 10 times table. We need another variable, though, to hold the 10. So add this to your variables:

int multiplyBy = 10;

The only other thing we need to do is to change the code between the curly brackets of the for loop. At the moment, we have this:

answer = answer + i;
listBox1.Items.Add( "i = " + i + " answer = " + answer.ToString() );

Delete these two lines and replace them with these two:

answer = multiplyBy * i;

listBox1.Items.Add(i + " times " + multiplyBy + " = " + answer.ToString());

The list box line is a bit messy, but examine the part between the round brackets:

i + " times " + multiplyBy + " = " + answer.ToString()

It's just a combination of variable names and direct text. The first line of the code, though, is a simple multiplication. We multiply whatever is inside of the variable called multiplyBy (which is 10) by whatever is inside of the variable called i. C# is adding 1 to the value of i each time round the loop, so the answer gets updated and then displayed in the list box.

Run your programme. Enter 1 in the first text box and 10 in the second text box. Click you button to see the ten times table:


So with just a few lines of code, and the help of a for loop, we've created a programme that does a lot of work. Think how much more difficult this type of programme would be without looping.

 

Exercise H
At the moment, we're multiplying by 10 and, therefore, displaying the 10 times table. Add another text box to your form. Add a label that asks users which times table they want. Use this value in your code to display the times table for them. So if your user types a 7 into your new text box, clicking the button would display the 7 times table in the list box. Here's what your programme should look like when you're finished (we've change the first two labels, as well):



When you complete this exercise, click your button a few times. You'll notice (as long as you have numbers in the text boxes) that the list box doesn't clear itself. You'll have this in your list box:


So the new information is simply added to the end. To solve this, add the following line anywhere before your for loop, but inside of your button code.

listBox1.Items.Clear();

So instead of using the Add() method, you use the Clear() method. This will clear out all the items in a list box. But can you see why the line of code would be no good inside of the loop? Or after the loop?


 

But that's enough of for loop. We'll now briefly explore two other types of loops: do loops and while loops.

C# Do loops and While Loops



 

As well as using a for loop to repeatedly execute some code, you can use a Do loop or a While loop. We'll start with the Do Loop.

 

C# Do Loops


Whichever loop you use, the idea is still the same: go round and round and execute the same code until an end condition is met. The difference with the Do and While loops is in the structure. Here's what the Do loop looks like:

do
{

} while (true);

Notice where the semi-colon is, in the code above. It comes right at the end, after the round brackets. But you start with the word do, followed by a pair of curly brackets. After the curly brackets, you type the word while. After while, and in between some round brackets, you type your end condition. C# will loop round and round until the end condition between the round brackets is met. Only then will it bail out. Here's an example, using our times table programme:

do
{

answer = multiplyBy * i;
listBox1.Items.Add(answer.ToString());
i++;

} while (i <= loopEnd);

So this time, we've used a Do Loop instead of a For Loop. The loop will go round and round while the value in the variable called i is less than or equal to the value in the variable called loopEnd. The other thing to notice here is we have to increment (add one to) the value in i ourselves (i++). We do this each time round the loop. If we didn't increment the value in i then it would always be less than loopEnd. We'd have then created an infinite loop, and the programme would crash. But we're really saying this:

"Keep Doing the code in curly brackets while i is less than or equal to loopEnd."

 

C# While Loops


While loops are very similar in structure to Do loops. Here's what they look like:

while (true)
{

}

And here's the times table code again:

while (i <= loopEnd)
{

answer = multiplyBy * i;
listBox1.Items.Add(answer.ToString());
i++;

}

While loops are easier to use than Do loops. If you look at the code above, you can see that the while part is at the start, instead of at the end like a Do Loop. The code you need to execute repeatedly still goes between curly brackets. And you still need a way for the loop to end (i++).

The difference between the two loops is that the code in a Do loop will get executed at least once, because the while part is at the end. With the while part at the beginning, your end condition in round brackets can already be true (i might be more than loopEnd). In which case, C# will bail out immediately, and the code in curly brackets won't get executed at all.


Deciding which loop to use can be quite tricky. Don't worry if you haven't fully understood how to use loops. You'll get lots more practice as you work your way through this book. But loops are difficult to get the hang of, and you shouldn't consider yourself a failure if you haven't yet mastered them. For now, we'll leave this complex subject, and end the section with a problem, and a solution.


Checking for Blank TextBoxes in C#



 


There's a problem with the text boxes on your times table programme. If you don't type anything at all in the text boxes, your programme will crash! Try it out. Start your programme and leave the text boxes blank. Now click your button. You should get a strange and unhelpful error message:


Visual Studio Express 2012 will just give your this rather plain error:


C# is highlighting the offending line in yellow. It does this because it can't convert the numbers from the text box and store them in the variables. After all, you can't expect it to convert something that's not there! To remedy this, you can use a method called TryParse.

To convert the numbers from the text boxes to integers, you've been doing this:

loopStart = int.Parse(textBox1.Text);

So you've Parsed the number in the text box, and turned it into an int. But this won't check for blank text boxes, and it won't check to see if somebody typed, say, the word three instead of the number 3. What you need to do is to Try and Parse the data in the text box. So you ask C# if it can be converted into a number. If it can't, you display an error message for your users. Here's some code that tries to parse the data from the first text box. It's a bit complex, so we'll go through it.


The first two lines set up some variables, an integer and a Boolean. The outputValue is needed forTryParse. You are trying to output a Boolean value (true or false) AND the string of text:

isNumber = int.TryParse(textBox1.Text, out outputValue);

So isNumber will be either true or false, depending on whether or not C# can convert the text box data into an integer. If you were trying to parse a double variable your code would be this, instead:

double outputValue = 0;
bool isNumber = false;

isNumber = double.TryParse(textBox1.Text, out outputValue);

The output value that you need is now a double (You're checking to see if C# can convert to a double value). The value of isNumber will still be either true or false (can it be converted or not).

After using TryParse, you then need to check that true or false value:

if (!isNumber)
{

MessageBox.Show("Type numbers in the text boxes");

}
else
{

//REST OF CODE HERE

}

If you remember the lesson on Conditional Operators, you'll know that this line:

if (!isNumber)

reads this:

If NOT true

If you prefer, you can write the line like this:

if (isNumber == false)

The line now reads:

"If isNumber has a value of false"

If isNumber is false, then you display an error for your users. If it's true, then it means that data from the text box can be converted properly. In which case, the rest of the code goes between the curly brackets of else.


If all that is a bit too complex then don't worry about it - you'll get there! In the next section, you'll be doing something far easier than loops and Conditional Logic: we'll show you how to add menus to your programmes.


But when you are first starting out, these are the two biggest hurdles to overcome: loops and Conditional Logic. When you understand these two difficult subjects then you are well on your way to becoming a programmer!

Adding Menus to Windows Forms in C#



 

In this section, we'll show how to add menus to your forms. You'll add File, Edit, and View menus, with items on each menu, and even sub menus. Here's what you will create:


So start a new project by clicking File > New Project from the menu at the top of Visual C#. Create a new Windows Application project. Call it anything you like. When your new form appears, you can add a menu bar quite easily.

Have a look at the Toolbox on the left of Visual C#. As well as the Common Control tools, there is a section for Menus and Toolbars. Click the plus symbol next to this to see the following:


The one you want is MenuStrip, which is highlighted in the image above. Double click MenuStrip and you'll see a menu bar appear at the top of your form:


But notice what has appeared at the bottom of your Visual C# window:


This is the MenuStrip object itself. The default Name for the MenuStrip is menuStrip1. If your MenuStrip is not selected, you can click on this icon at the bottom. When you do, you'll see all the Properties for the MenuStrip appear in the Properties Window on the right hand side of Visual C#.

Adding items to your menus is quite simple. Click inside of the area at the top, where it says "Type Here". Now type the word File.


Hit the Enter key on your keyboard and your menu will look like this:


What you have done is to create the main menu item. To add items to your File menu, click inside of the second "Type Here" area pictured above. Now type the word New. Hit the Enter key on your keyboard to add the menu item:


Click back on the word New after you have hit the enter key. This will select just this menu item, and no other. Once you create a menu item it has its own Properties that you can change. With the New item selected, have a look at the Properties Window on the right hand side of Visual C#:


The Property we're interested in is the Name. It's a bit too long at the moment. So change it tomnuNew, as in the image below:


If you scroll down, you'll also see a Text property. It will say New, at the moment. It says New because that's what you typed in the menu bar when you created this item. You could change this here, if you wanted to. But leave the Text property on New.

Click back on your menu at the top of your form, and then into the "Type here" area just below New. Type the word Open:


Hit the Enter key on your keyboard to create the Open menu item. Change its Name property, just like you did for the New item. Change the name to mnuOpen.

Create a Save menu item, underneath Open. Change its Name property to mnuSave. Your File menu will then look like ours below:


We'll now create just two more menu items, a dividing line, and a Quit item. To create a dividing line, click inside of the "Type Here" area below Save. Now type a hyphen (just to the right of the zero key on UK keyboard). When you press the Enter key, C# will turn the hyphen into a dividing line. It should look like this:


Add the Quit item below your dividing line. Change the Name property to mnuQuit. Your File menu is now complete. To see what it looks like, run your programme. You should have a blue toolbar running across the top with a File menu. Click your File menu:


Of course, none of the menus work, because you haven't written any code for them yet. We'll do that soon. But just in case you don't fancy a blue menu bar running across the top, this is easily changed. Click the red X to halt your programme and return to Visual C#. Now click anywhere on the blue menu to select it. Or click on menuStrip1 at the bottom of the screen.

With the MenuStrip selected, have a look at its Properties in the Property Window. Locate one calledRenderMode:


Click the down arrow to see more options. The Professional one doesn't do much. So select System.


Now have a look at your MenuStrip. It should have changed to this:


When you run the programme, it looks like the one in the image below:


 

In the next part, you'll learn how to add sub menus.

Sub Menus in C# .NET



 


You can add Sub Menus just as easily. A Sub menu is one that opens out from a main menu item.

Halt your programme and return to your form. Click on the New item to select it. You should see a "Type Here" box appear to the right of New:


Click Inside of this box and type View Project. Hit the enter key and type View Files in the box below this. Your menu will then look like this:


When the form is run, the Sub Menu will look like this:


Sub menus are quite easy to add! In the mext lesson, you'll learn how to add shortcuts to your menu 

Menu Shortcuts in C# .NET




Menus usually have shortcuts. These are the underlined letters that you see when you click a menu. They sometimes have a shortcut key combination to the right of the menu item. For example, here's the File menu from Visual C# with all the underlines and key combinations showing:


To see these, you need to hit the ALT key on your keyboard. When you see the underlined letters, press the key that corresponds to the underlined letter. Pressing the "F" key, for example, will then cause the menu to drop down. Pressing any of the underlined letters on the File menu will implement that menu item. (In our edition of Visual C# Express, pressing the letter P only switches back and forward between the first two items. The other letters work OK, though.)

You can also use the key combinations to the right of the menu item. Holding down CTRL + SHIFT + N at the same time will cause the New Project dialogue box to appear.

To add shortcuts to your own menus, click your File item to select it. Now have a look at its Properties in the Property Window. Scroll down until you locate the text item:


To add an underline to any of the letters, you use the ampersand symbol (&) before the letter you want to use as a shortcut. In the image below, we've added an ampersand just before the "F" of File:


And here's what the menu looks like with the ampersand added:


As you can see, there's now a line underneath the letter "F". In the next image, we've added more underlines to the rest of the File menu:


Add the same underlines to your own File menu. Remember: click a menu item to select it, locate the text property, and add an ampersand before the letter you want to use as a shortcut. When you run the programme, don't forget to press the ALT key on your keyboard, otherwise you won't see the underlined letters.

The key combination shortcuts are just as easy to add. Click on your New menu item to select it. Locate the ShortcutKeys Property in the Properties Window:


At the moment, it's set to None. Click the down arrow to see the following options:


The Modifiers are the CTRL, Shift, and ALT keys. You can select one or all of these, if you want. To activate a shortcut, you would then have to hold down these keys first. So if you want your users to hold down the CTRL and Shift keys, plus a letter or symbol, then you would check the relevant Modifier boxes above.

The letters and symbols can be found on the Key drop down list. Click the down arrow to see the following:


In the image above, we've gone for the CTRL modifier, and the letter "N". Clicking back on the menu, here's what it now looks like:


As you can see, the shortcuts for the New menu item are an Underline, and Ctrl + N.

Have a look at the next image, and add the same Shortcut Keys to your File menu:


The ones you are adding are the final three: Open, Save and Quit. We'll get to coding the menu items shortly, but here's an exercise to complete. (Don't skip this exercise because you'll need the menu items!)

 

Exercise
Add an Edit menu to your menu bar with the following items:



Include the underline shortcuts, and the key combination shortcuts. For the Name Property of each menu item, use the following:

Undo: mnuUndo
Cut: mnuCut
Copy: mnuCopy
Paste: mnuPaste

Exercise
Add a View menu to your menu bar with the following items:



Again, include the underline and key combination shortcuts. Set the Name Property of your menu items to the following:

View Text Boxes: mnuViewTextBoxes
View Labels: mnuViewLabels
View Images: mnuViewImages

OK, it's now time to do some coding for the menu items you have created

C# Code for your Quit Menu




Of course, a menu is no good if nothing happens when you click an item. So we need to add code behind the menu items. We'll start with the Quit item, which should be on your File menu. There's only one line of code for this.

Return to your form, and click the menu strip. Click the File item to see its menu. Double click on yourQuit item and the coding window should open. Your cursor should be flashing between the curly brackets of the Quit code stub:


Notice that the Name you gave your menu item is used in the code stub: mnuQuit. But when a user clicks your Quit menu, you want the programme to end. To close down a Windows application, you can use this:

Application.Exit( );

So add that line of code between the curly brackets of your Quit code stub. Run your programme and test it out. Hit the CTRL and SHIFT keys, and then the letter Q on your keyboard. The programme should close straight away. It does this because of the key combination shortcuts you added.

To see your underline shortcuts in action, start your programme again. Press the ALT key on your keyboard and you should see all the underlines appear for File, Edit and View. Press the letter "F" on your keyboard (the underlined letter), and the menu should drop down. Now press the letter Q on your keyboard. Because this is the underlined letter, the programme should exit.

You can add more code to menu items - anything you like, in fact. Something you do see on Quit menus is a message box:

"Are you sure you want to Quit?"

To add a message box to your own code, try this:

if (MessageBox.Show("Really Quit?", "Exit", MessageBoxButtons.OKCancel) == DialogResult.OK)
{

Application.Exit();

}

The first two lines should be one line in your code. It's only on two lines here because there's not enough room for it on this page. But in between the round brackets of an if statement, we have a message box:

MessageBox.Show("Really Quit?", "Exit", MessageBoxButtons.OKCancel)

This will get you a dialogue box with OK and Cancel buttons. C# will wait until the user clicks a button. Our code uses an if statement to test which button was clicked. To see which one the user clicked, you add this on the end:

== DialogResult.OK

So the line reads "IF the result of the dialogue box was that the OK button was clicked, then Exit the Application."

 

In the next part, you'll see how to code for your Edit menu.

Copy and Paste in C# .NET



 


To Copy something to the Clipboard, you highlight text and click a Copy item on an Edit menu. Once the data is copied to the Clipboard, it can be Pasted elsewhere. We'll implement this with our menu system.

Double click the Copy item on your Edit menu. You'll be taken to the code stub for your Copy menu item. Add the following code between the curly brackets:

textBox1.Copy();

Using the Copy method of text boxes is enough to copy the data on to the Windows Clipboard. But you can first check to see if there is any highlighted text to copy. Change your code to this:

if (textBox1.SelectionLength > 0)
{

textBox1.Copy();

}

We're using an if statement again. This time, we are checking the SelectionLength property of text boxes. The length returns how many characters are in the text that was selected. We want to make sure that it's greater than zero.

We'll use the second text box to Paste. So access the code stub for your Paste menu item, using the same technique as before. Add the following between the curly brackets of your Paste code:

textBox2.Paste();

Notice that we're now using textBox2 and not textBox1. After the dot, you only need to add the Paste method.

Try your Edit menu out again. Highlight the text in the first text box. Click Edit > Copy. Now click into your second text box and click Edit > Paste.

You can also check to see if there is any data on the Clipboard, and that it is text and not, say, an image. Add this rather long if statement to your code:

if (Clipboard.GetDataObject().GetDataPresent(DataFormats.Text) == true)
{

textBox2.Paste();
Clipboard.Clear();

}

Getting at the data on the Clipboard can be tricky, but we're checking to see what the DataFormat is. If it's text then the if statement is true, and the code gets executed. Notice the last line, though:

Clipboard.Clear();

As you'd expect, this Clears whatever is on the Clipboard. You don't need this line, however, so you can delete it if you prefer. See what it does both with and without the line.

 

In the next part, we'll code for the View menu.

The View Menu



 


We have three items on our View menu. But we'll only implement two of them. For the first one, View Text Boxes, we'll show you a handy programming technique with Boolean variables - how to toggle them on and off.

So return to your form, and double click the menu item for View Text Boxes. C# will generate the code stub for you:


What we'll do is to hide the text boxes when the menu item is clicked, and unhide the text boxes when you click again. A check icon will then appear or disappear next to the menu item. Here's an image of what we'll be doing:


To place a check mark next to a menu item, you use the Checked Property of the menu item. Add this to your View Textboxes code stub, in between the curly brackets:

mnuViewTextboxes.Checked = true;

So you just type a dot after the Name of your menu item. Then select the Checked property from the IntelliSense list. Checked is a Boolean value that you either set to true or false (it's either got a check mark next to it or it hasn't).

Run your programme and click your View Textboxes menu item. You should see a check appear. It does so because the default value for the Checked property is false. It only becomes true when you click the menu item, thereby running the code you added.

The question is, how do you get the Check mark symbol to disappear when it's clicked again? Obviously you need to set it to false, meaning not checked. But what's the code?

A handy programming technique is to toggle Boolean values off and on. You do it with the aid of the NOT operator ( ! ). Amend your code to this:

mnuViewTextboxes.Checked = !mnuViewTextboxes.Checked;

So instead of setting the Checked value to true, we have this:

!mnuViewTextboxes.Checked;

This says, "NOT Checked". But doesn't mean "Unchecked". What you are doing is setting the Boolean variable to what it is currently NOT. Remember: Checked can either be true OR false. So if Checked is currently true, set it to false, and vice versa. The result then gets stored back in the Property on the left of the equals sign.

Run your programme and try it out. Click the menu item to see the Check symbol. Click it again and it will disappear. This toggling of Boolean variables is quite common in programming, and can save you a lot of tricky coding!

To actually do something with the text boxes, though, you can add an if statement to examine whether the variable is true. What we'll do is make the text boxes visible if there's a Check, and not visible if there isn't a Check. Add this code just below the line you already have:

if (mnuViewTextboxes.Checked)
{

textBox1.Visible = true;
textBox2.Visible = true;

}
else
{

textBox1.Visible = false;
textBox2.Visible = false;

}

The Property we are changing is the Visible Property of text boxes. As its name suggests, this hides or un-hides an object. Again, it's a Boolean value, though. So we could have just done this:

textBox1.Visible = !textBox1.Visible;

The use of the NOT operator will then toggle the Visibility on or off. We added an if statement because it's handy to actually examine what is in the variable, rather than just assuming.

One line you may puzzle over is this:

if (mnuViewTextboxes.Checked)

The part in round brackets could have been written like this, instead:

if (mnuViewTextboxes.Checked == true)

For if statements, C# is trying to work out if the code in round brackets is true. So you can leave off the "== true" part, because it's not needed. If you want to check for false values, you can use the NOT operator again. Like this:

if (!mnuViewTextboxes.Checked)

This is the same as saying this:

if (mnuViewTextboxes.Checked == false)

Using the NOT operator is considered more professional. They mean the same, though, so use which one is better for you.

 

In the next part you'll see how to add images to your C# programmes.

Adding Images in C# .NET




You have seen the Open File dialogue box countless times. It's the one that appears whenever you click File > Open on a Windows machine. You then navigate through folders, searching for the file you want to open. For our View Images menu, we'll do something slightly more complex - we'll have our own Open File dialogue box that allows you to select images from your computer. When you select an image, it will then appear in a new control on your form.

So we need a place on our form where we can store images. We'll use a Picture Box.

Have a look at the Toolbox on the left hand side of Visual C#. Under Common Controls, locatePictureBox:


Once you've select the PictureBox tool. Click on your form once to add a new PictureBox control. Your form should then look like this:


The PictureBox control is blank when you first add one. To add an image to it at Design Time, have a look at the Properties Window. Locate the Image property:


Click the button with the three dots on it to see a dialogue box appear:


Click the Import button at the bottom and you'll see a standard Open dialogue box. Search your hard drive for a suitable image. Because you have "Project resource file" selected, C# will copy the image to a folder in your project. (This is handy if you want to send your programme to anyone else.)

In the image below, we've gone for a picture of a planet:


Click OK and you'll be taken back to your form:


Notice that the image is too big for the PictureBox. Locate the SizeMode property in the Properties Window:


As you can see, there are a few to choose form. Select AutoSize, and the PictureBox will automatically stretch to the size of your image:


If you run your programme, you'll see the image appear on the form. It won't have a border, though. If you want a border, explore the BorderStyle Property of your PictureBox control.

 

In the next part, you'll see how to add an Open File dialogue box to a project, allowing you to select any image you want.

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:


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.

 

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

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 youFile > 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.

 

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

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


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:


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:


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:


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:


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:


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:


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 theChecked 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:


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:


Return to your code, and add three more if statements. When you are finished, your coding window should look like this one:


When you run your programme and check all the boxes, the message box will look like this, after the button is clicked:


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:



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.

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):


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:


Holding the mouse pointer over the red wavy line gives the following message:


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:


 

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:


Holding the mouse pointer over the green underlines gives the following message:


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.

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:


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):


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:


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.

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:


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 theendLoop 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:


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:


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:


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 onGeneral. 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:


Move your mouse pointer over the letter variable and C# will show you what is currently in this variable:


Now hold your mouse over strText to see what is in this 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:


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.

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:


Keep pressing F10 and the values will change. Here's what is inside of the variables after a few spins round the loop:


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!


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# toTry 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);

}

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:


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:


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.

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:


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:


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:


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.

In the next part, you'll see how to pass values to your Methods.

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:


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 parameterfirstNumber. 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:


So we've set up a new int variable called answer. We're then adding up the variables firstNumberand 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:


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:


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:


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:


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 andnumber2. 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 calledfirstNumber 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.

You will also want to get values back from your Methods, and you'll see how to do that in the next lesson.

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:


If you add a few comments, your coding window should look like ours:


So we have one button and two Methods. Before we explain the new Method, double click theSubtract button on your form to get at its code. Then add the following:


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:


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:






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.)

We'll leave Methods for now. But we'll be using them a lot for the rest of this book! To help your understanding of the topic, try this exercise.

 

Exercise J
Add two more Methods to your code, one to Multiply, and one to Divide. Add code to your Multiply and Divide buttons that uses your new Methods. When you run your programme, all four buttons should work.


Arrays in C# .NET



 

The variables you have been working with so far have only been able to hold one value at a time. Your integer variables can only hold one number, and your strings one chunk of text. An array is a way to hold more than one variable at a time. Think of a lottery programme. If you're just using single variables, you'd have to set up your lottery numbers like this:

lottery_number_1 = 1;
lottery_number_2 = 2;
lottery_number_3 = 3;
lottery_number_4 = 4;
etc

Instead of doing that, an array allows you to use just one identifying name that refers to lots of numbers.

 

How to set up an Array


You set up an array like this:

int[ ] lottery_numbers;

So you start with the type of array you need. In the line above, we're telling C# that the array will hold numbers (int). After the array type, you need a pair of square brackets. There should be no space between the array type and the first bracket. After the square brackets then type a space, followed by the name you want to use for your array, lotter_numbers in our case.

If your array needs to hold floating point numbers, you'd set your array up like this:

float[ ] my_float_values;

An array that needs to hold text would be set up like this:

string[ ] my_strings

So it's pretty much just like setting up a normal variable, except you type a pair of square brackets after int, or float, or string.

The next thing you need to do is to tell C# how big your array will be. The size of an array is how many items it is going to hold. You do it like this:

lottery_numbers = new int[49];

So the name of your array goes before an equals sign ( = ). After the equals sign, you type the wordnew. This tells C# that it is a new object. After a space, you need the array type again (int for us). Next comes some square brackets. This time, however, you type the size of the array between the brackets. In the code above, we're saying that the array will hold 49 numbers.

So the two lines would be:

int[] lottery_numbers;
lottery_numbers = new int[49];

If you prefer, you can put all that on one line:

int[ ] lottery_numbers = new int[49];

But you're doing two things at once, here: before the equals sign, you're telling C# that you want to set up an array; after the equals sign, you're creating a new array object of a particular size.

 

Assigning values to your arrays


So far, you have just set up the array, and created an array object. But the array doesn't yet hold any values. (Well it does, because C# assigns some default values for you. In the case of int arrays, this will be just zeros. But they're not your values!)

To assign a value to an array, you use the square brackets again. Here's the syntax:

array_name[position_in_array] = array_value;

So you start with the name of your array, followed by a pair of square brackets. In between the square brackets, you need a position in your array. You then type an equals sign, and the value that is going in that position. Here's an example using our lottery numbers:

lottery_numbers[0] = 1;
lottery_numbers[1] = 2;
lottery_numbers[2] = 3;
lottery_numbers[3] = 4;

First of all, note that the first position in a C# array is zero, and not 1. This is slightly confusing, and can trip you up! But we're telling C# to assign a value of 1 to the first position in the array, a value of 2 in the second position, a value of three in the third, and so on. Just bear in mind that array positions start at 0.

Another way to assign values in array is by using curly brackets. If you only have a few values going in to the array, you could set it up like this:

int[] lottery_numbers = new int[4] { 1, 2, 3, 4 };

So we've set up the array the same way as before - all on one line. This time, we have a pair of curly brackets at the end. In between the curly brackets, type the values for your array, and separate each value with a comma.

In the next lesson, you'll see how to work with arrays and loops.

Arrays and Loops in C# .NET



 


Arrays come into their own with loops. The idea is that you can loop round each position in your array and access the values. We'll try a programming example, this time.

So start your C# software up, if you haven't already, and create a new windows application. Add a button and a list box to your form. Double click your button to get at the code. For the first line, add code to clear the list box:

private void button1_Click(object sender, EventArgs e)
{

listBox1.Items.Clear();

}

For the second and third lines, set up an integer array:


Now add some values to each position in the array:


If you wanted to, you could display each number in the list box like this:

listBox1.Items.Add( lottery_numbers[0] );
listBox1.Items.Add( lottery_numbers[1] );
listBox1.Items.Add( lottery_numbers[2] );
listBox1.Items.Add( lottery_numbers[3] );

So to get at the value in an array, you just use the array name and a position number, known as the index number:

lottery_numbers[0];

This is enough to display what value is at this position in the array. Try it out. Add the list box code to your programme:


Run your programme and click your button. Your form should look like this:


So the numbers 1 to 4, the values we placed in the array, are now displayed in the list box. Halt your programme and return to the coding window.

If you had a long list of numbers to display, you don't really want to type them all out by hand! Instead, you can use a loop. Add the following loop to your code:

for (int i = 0; i != (lottery_numbers.Length); i++)
{

listBox1.Items.Add( lottery_numbers[i] );

}

Now delete all of your listbox lines. Your code should then look like this:


When you run the programme, the numbers should display in the list box again. But how does it work?

The code works because the array index number is matching the loop variable number. Here's some images to show what's happening:



In the first image, we've highlighted the int variable we'll called i. This gets set to zero, which is the start of the loop. In the second image, we see the i variable again. This time, it is between the square brackets of the array name. The first time round the loop, the value in i is 0. The i variable gets 1 added to it each time round the loop. So the second time round, it's value will be 1, the third time 2, etc. So this is happening:


The value in each position is then accessed, which for us was the numbers 1 to 4.

One thing to make note of is this part of the for loop:

i != (lottery_numbers.Length)

Length is a property of arrays that you can use. It refers to the number of items in your array. So we're saying, "Keep looping while the value in i does not equal The Length of the array".

 

Use a loop to assign values to an array


You can also use a loop to assign values to your arrays. In the code below, we're using a loop to assign values to our lottery_numbers array:

for (int i = 0; i != (lottery_numbers.Length); i++)
{

lottery_numbers[i] = i + 1;
listBox1.Items.Add(lottery_numbers[i]);

}

The only thing that has changed with our for loop is the addition of this line:

lottery_numbers[i] = i + 1;

The first time round the loop, the value in i will be zero. Which gives us this:

lottery_numbers[0] = 0 + 1;

The second time round the loop, the value in i will be 1. Which gives us this:

lottery_numbers[1] = 1 + 1;

But what we are doing is manipulating the index number (the one in square brackets). By using the value of a loop variable, it gives you a powerful way to assign values to arrays. Previously, we did this to assign 4 numbers to our array:

lottery_numbers[0] = 1;
lottery_numbers[1] = 2;
lottery_numbers[2] = 3;
lottery_numbers[3] = 4;

But if we need 49 numbers, that would be a lot of typing. Contrast that to the following code:


Here, we've set up the array for 49 numbers. We've used a loop to assign the values 1 to 49 to each position in our array. So with one small change, we've saved ourselves an awful lot of typing!

Change your own code to match ours and try it out. When you click the button on your form, all 49 numbers should appear in the list box:


As an exercise, halt your programme and change the index number of the array from 49 to 1000. Run your programme and test it out. What you've done is to set up an array and fill it with a thousand values!

In the next lesson, you'll see how to set up an array when you don't know how many items are in it

Set the Size of a C# array at RunTime



 


The size of an array refers to how many items it holds. You've seen that to set the size of an array, you do this:

int[ ] someNumbers;
someNumbers = new int[10];

Or this:

int[ ] someNumbers = new int[10];

But sometimes, you just don't know how big the array needs to be. Think of a programme that pulls information from a database. You want to loop round and check how many of your customers still owe you money. You've decided to hold all the data in an array. But how big does the array need to be? You can't set a fixed size before the programme runs, simply because the number of people owing you money could change. It could be low one month, and high the next.

To solve the problem, you can set the array size at runtime. This would mean, for example, setting the array size after a button is clicked. To see how it works, add another button to your form, along with a text box. Your form should then look something like this:


We've typed the number 5 in the text box, but you can have any number you like.

Double click your button and enter the following code:

int aNumber = int.Parse(textBox1.Text);

int[ ] arraySize;
arraySize = new int[aNumber];

The first line of the code gets the value from the text box and places into a variable we've calledaNumber. The second line sets up an array as normal. But look at the third line:

arraySize = new int[ aNumber ];

Now, the figure between the square brackets of int is not a number we've just typed. It's a variable name. Since the value of the variable is coming from the text box, the size of the array will be whatever number is typed in the text box.

Add the following loop to your code, which just assigns values to the array, and places them in the list box on your form:

for (int i = 0; i != (arraySize.Length); i++)
{

arraySize[i] = i + 1;

listBox1.Items.Add(arraySize[ i ]);

}

Run your programme and click your button. You should see this in your list box:


Now delete the 5 and type a different number. You should see the number from 1 to whatever number you've just typed.

This technique can be used whenever your programme needs to get its array size at runtime - assign to a variable, and use this variable between the square brackets of your array.

 

Use an array in a times table programme


To get some more practice with arrays, add another button to your form. Set the text to be this:

Exercise: Times Table

Now double click the button and add the following code:


When you run your programme and click the button, your form should look something like ours:


Notice that the 5 times table is displayed in the list box. Now try the following exercises:

Exercise K

The first item in the array, arrayTimes[0], doesn't get used - why is this?


 

Exercise L

Amend the code so that the times table from 1 to 10 displays in the list box, not 1 to 9


 

In the next lesson, we'll take a look at something called a Mutli Dimensional Array.

Multi Dimensional Arrays in C# .NET



 


Your arrays don't have to be single lists of items, as though they a were a column in a spreadsheet: you can have arrays with lots of columns and rows. These are called Multi-Dimensional arrays. For a 1-dimensional array, the ones you've been using, it would look like this:


For a 2-dimensional array, it would look like this:


So if you wanted to get at the value of 2000 in the table above, this would be at array position 1 in column 2 (1, 2). Likewise, the value 400 is at position 3, 1.

To set up a 2-dimensional array, you use a comma:

int[ , ] arrayTimes;

You then need a number either side of the comma:

arrayTimes = new int[5, 3];

The first digit is the number of Positions in the array; the second digit is the number of Columns in the array.

Filling up a 2-dimensional array can be quite tricky because you have to use loops inside of loops! Here's a programme that fills a 2-dimensional array with the values in the table above:


Notice the two for loops in the code above, one inside of the other. The first loop is setting the value of the Rows (array Positions), and the second loop is setting the value of the Columns.

You don't have to understand the code, at this stage of your career! But see if you can puzzle it all out. For the adventurous, add another button to your form. Enter the code above. Now add a second double for loop, and print out the array values in your list box. See if you can get the same values as ours, in the form below:


This is a tough exercise, so give yourself a giant pat on the back, if you get there!

In the next lesson, you'll see how to deal with Arrays and Text.

Arrays and Text in C# .NET



 


You've seen how to place numbers into an array. But you can also place strings of text. In the next section, we're going to be studying the subject of Strings more closely. We're going to develop a hangman game that makes use of arrays and text. So a reasonable understanding of how to place text into an array will make the going easier!

Add a new button to your form, and set the Text property to String Arrays. Then double click your button to get at the code.

To place text into an array, you set up your array as you normally would, except you use the keywordstring instead of int. Like this:

string[] arrayStrings;
arrayStrings = new string[5];

So the above code would set up an array that is going to hold strings of text. There will be five positions in the array.

Add the code above to your button.

To place values in the array, it's just normal variable assignment, with a pair of square brackets after the variable name:

arrayStrings[0] = "This";
arrayStrings[1] = "is";
arrayStrings[2] = "a";
arrayStrings[3] = "string";
arrayStrings[4] = "array";

Add the above to your code, and then we'll discuss ForEach Loops.

 

The ForEach Loop


To access the values in each position of your array, you could use a for loop, as you have been doing. Like this:

for (int i = 0; i != (arrayStrings.Length); i++)
{

listBox1.Items.Add( arrayStrings[i] );

}

But there's another type of loop that you haven't met yet called a foreach loop. This comes in handy when you're trying to access items in a collection, which you'll see how to do shortly. But add this to your code, instead of a for loop:

foreach ( string arrayElement in arrayStrings )
{

listBox1.Items.Add( arrayElement );

}

Notice where all the keywords are in the loop code above, the ones in blue. You start with the foreachkeyword, followed by a pair of round brackets. In between the round brackets, we have this:

string arrayElement in arrayStrings

This is really two parts in one. In the first part, string arrayElement, you set up a new variable. The new variable will hold the elements (array values) from each position in your array. The second part, inarrayStrings, is where you tell C# the name of the array or collection you want to access. C# will then loop round all the positions in your array, and place the value at that position into your new variable (arrayElement, for us). You can then do something with the value in the new variable. All we are doing in our loop is to display the value in a list box. Here's a colour-coded image that may help you to understand what's going on:


Notice that for the array, you don't need the square brackets anymore. The neat thing about foreach loops is that you don't need to use index numbers, like you do with ordinary for loops.

Run your programme and click the button. The list box on your form should then look like ours:


As we said, you'll work with string arrays in the next section, so we'll leave them for now. The final part of this section deals with objects closely associated with arrays - collections.

C# Collections - Lists



 


Arrays are very useful for holding lots of values under the same name. But there is also something called a Collection that does a similar job. In fact, there's an inbuilt group of Classes in C# specifically for Collections. They can be quite powerful.

With an array, you store data of the same type. So one array can only hold, say, numbers, but not letter. And an array set up as string can't hold numbers. So you can't do this, for example:

arrayPos[0] = 1;
arrayPos[1] = "two";

The first position holds a number and the second position holds text. C# won't let you do this in an array. But you can do it in a collection known as a Hashtable.

Collections can also make it easier to do things like sorting the data in your lists, deleting items, and adding more items. We'll start with the collection class called Lists.

 

Lists


You use a List when your collection may need items adding to it, deleting from it, or needs sorting. For example, suppose you are teacher with a class of ten children. You could keep a list of the children's names, add new students, delete ones who leave, and even sort them alphabetically! If you used a normal array, it would be difficult to do these things.

So start a new C# project. Add a button and a listbox to your new form. Double click the button to get at the coding window. Now have a look near the top and you'll see a list of using statements (lines 1 to 7 in the image below):


 

The using statement that is needed for lists is the one that says System.Collections.Generics. If you can't see it as one of your using statements, add it yourself.

To set up a List, double click the button on your form to create a code stub. Now add the following line:

List<string> students = new List<string>();

You start with the word, List. Then comes a pair of pointy brackets. In between the pointy brackets you need a variable or object type. We've used string. What this tells C# to do is to set up a List that will hold string values. The list itself is called students. After an equal sign, we have the new keyword. Next comes the List<string> part again. This time, however, it's followed by a pair of round brackets, telling C# to create a new list of string values.

Your code window will look something like this:


After setting up the List, you need to fill it with data. Add the following three lines to your code:

students.Add("Jenny");
students.Add("Peter");
students.Add("Mary Jane");

Your coding window will then look like this:


After typing the name of your List (students, for us), you may have seen the C# IntelliSense list appear:


This is a list of all the Methods and Properties that a List has. The one that you use to add items to your List is called, not surprisingly, Add( ). Between the round brackets of Add( ), you type the data that you want to add to your List:

students.Add( "Jenny" );

For every item in your collection, you need a new line that Adds items.

To access the items in your List, you can use a foreach loop. Add this to your button code:

foreach (string child in students)
{

listBox1.Items.Add( child );

}

So we're looping round all the items in the List, and then adding them to the listbox.

You can also use an ordinary for loop:

for (int i = 0; i < students.Count; i++)
{

listBox1.Items.Add( students[i] );

}

Notice that the end condition is students.Count. Count is a property of Lists that tells you how many items is in it. Inside the for loop, we're using square brackets with the index number inside. This is just like the normal arrays you used earlier.

But if you want to loop round a collection, the above code is not the right choice. A better choice is a foreach loop.

A foreach loop ends when no more items in your collection or array are left to examine. Unlike a normal for loop, you don't have to tell C# when this is - it already knows what's in your collection, and is clever enough to bail out of the foreach loop by itself.

You can add a new item to your List at any time. Here's an example to try:


So we're adding a fourth student to the List, Azhar, and then displaying the item in the listbox.

Add the new code to your button. Run your programme and click your button. Your form will look something like this:


 

Sorting a List


Sorting a List alphabetically is quite straightforward. You just use the Sort Method. Like this:

students.Sort();

And here's some code to try out. The new lines should be added at the end of your current code:

students.Sort();

listBox1.Items.Add("=================");

foreach (string child in students)
{

listBox1.Items.Add(child);

}

Run your programme and try it out. Here's what your listbox will look like after the button is clicked:


As you can see, the items have been sorted alphabetically, in ascending order. You can have a descending sort, if you prefer. One way to do this is with the Reverse method:

students.Reverse( );

No extra coding is needed!

 

Removing items from a List


To remove an item from your list, you can either use the Remove or the RemoveRange methods. The Remove method deletes single items from the List. You use it like this:

students.Remove( "Peter" );

In between the round brackets of Remove, you simply type the item you want to remove.

If you want to remove more than one item, use RemoveRange. Like this:

students.RemoveRange( 0, 2 );

The first number between the round brackets of RemoveRange is where in your list you want to start. The second number is how many items you want to remove. Here's some code to try at the end of your button:

students.RemoveRange(0, 2);

listBox1.Items.Add("=================");

foreach (string child in students)
{

listBox1.Items.Add(child);

}

But that's enough of Lists. There's lots more that you can do with them, and they are worth researching further.

The final Collection we'll look at is called a Hashtable.

C# Collections - HashTables



 


You use an Hashtable when you want to store information based on Key/Value pairs. For example, the name of a student AND the score in an exam. This allows you to mix text and numbers. (In other programmes, Hashtables are known as associative arrays.)

Add a new button to your form, and double click it to get at the code. Now have a look at the using statements at the top. Add the following to the end of the list:

using System.Collections;

You already have a System.Collections.Generic statement, but a Hastable is not part of this collection - it's part of the normal Collections namespace.

Click inside the code stub for you button. You setting up the Hashtable like this:

Hashtable students = new Hashtable();

This creates a new object called students. It's going to be an Hashtable object.

There are two ways you can add data to your Hashtable. Like this:

students["Jenny"] = 87;
students["Peter"] = "No Score";
students["Mary Jane"] = 64;
students["Azhar"] = 79;

Or like this:

students.Add("Jenny", 87);
students.Add("Peter", "No Score";);
students.Add("Mary Jane", 64);
students.Add("Azhar", 79);

The first method uses a pair of square brackets:

students["Jenny"] = 87;

In between the square brackets, you type what's known as the Key. So this particular entry in the Hashtable is called "Jenny". After an equals sign, you then type the Value that this Key will hold. Notice that three of the entries are number values, and one (Peter) is text.

The second way to store values in an Hashtable is to use the Add Method:

students.Add("Jenny", 87);

In between the round brackets of Add( ), you first type the Key name. After a comma, you type the Value for that Key.

There is a difference between the two. If you use the Add method, you can't have duplicate Key names. But you can if you use the square brackets. So this will get you an error:

students.Add("Jenny", 87);
students.Add("Jenny", 35);

But this won't:

students["Jenny"] = 87;
students["Jenny"] = 35;

To try Hashtables out for yourself, add the following code to your button:

Hashtable students = new Hashtable();

students["Jenny"] = 87;
students["Peter"] = "No Score";
students["Mary Jane"] = 64;
students["Azhar"] = 79;

foreach (DictionaryEntry child in students)
{

listBox1.Items.Add("student: " + child.Key + " , Score: " + child.Value);

}

Before running the code, have a look at the foreach loop. Inside of the round brackets, we have this:

DictionaryEntry child

This sets up a variable called child. But note the type of variable it is: a DictionaryEntry. C# uses an object of this type when using the foreach loop with Hashtables. That's because it automatically returns both the Key and the Value.

Notice, too, what we have between the round brackets of the listbox's Add method:

"student: " + child.Key + " , Score: " + child.Value

The red bold are the important parts. After typing the name of your variable (child, for us) and a full stop, the IntelliSense list will appear. Key is a property that returns the name of your Key, and Value is a property that returns whatever you placed inside of that Key.

Run your programme and click your button. The form on your listbox will then look like this:


But just like the List, you can Add new items, and remove old ones. To Remove an item, you do it like this:

students.Remove("Peter");

So you refer to the Key name, and not the Value, when you use the Remove method.


In the next lesson, we'll take a look at Enumerations.


Enumerations in C# .NET


You can create your own collections of things with something called Enumeration. Suppose you wanted to set up a list of subjects that students can study, but don't want to keep typing the list out all the time. Instead, you can set up an Enumerated list. Here's how.

Add a new button to the form and set the text property as Enumeration. Double click your button to get at the coding window. Now add the enum part below to your code:


You start with the word enum. After a space, you type a name for your enumerated list. In between a pair of curly brackets, you type the list itself. We've added five subjects to our lists; English, IT, Science, Design, Math.

To use your enumerated list, click inside of your button code. Add the following line:

Subjects newSubject = Subjects.Science;

So you type the name of your enumerated list followed by a space. After coming up with a variable name, type an equals sign. Type the name of your list again, followed by a dot. You will then see the items in your list:


Select one of the items from your list, and end the line with a semicolon.

What you have done is to set up your own value type, with its own name (Subjects). The values in your type are the ones you added between the curly brackets. They also have an underlying number. So the first item is 0, the second item is 1, the third 2, etc.

To display it in a message box as a string, the code would be this:

MessageBox.Show( newSubject.ToString( ) );

It needs converting because it's an enumerated type - it's not a string.

If you want to get at the underlying number, you would do the conversion like this:

Subjects newSubject = Subjects.Science;

int enumNumber = (int)newSubject;

In other words, convert to int in the usual way, by putting (int) before what it is you want to convert. You could then loop round and do some checking. Something like this:

for (int i = 0; i < 4; i++)
{

if (i == 2)
{

MessageBox.Show("You're taking Science");

}

}

Enumerated lists are good for when you have a list of custom items and don't want to use an array.

 

And that ends the section on arrays and collections. There's still an awful lot we haven't yet covered on the subject, especially for Collections. But it's enough to be going on with, for a beginner! In the next part, we'll have a close look at Strings.

String Manipulation in C# .NET



 

Quite often, strings of text need manipulating. Data from a textbox need to be tested and checked for things like blank strings, capital letters, extra spaces, incorrect formats, and a whole lots more besides. Data from text files often needs to be chopped and parsed before doing something with it, and the information your get from and put into databases routinely needs to be examined and worked on. All of this comes under the general heading of String Manipulation.

Later in this section, you're going to be creating your very own Hangman programme. The programme will make use of string manipulation techniques. Let's go through a few of the things that will help you deal with strings of text.

 

C# String Variables


You've already worked with string variables a lot in this book. But there's a lot more to them than meets the eye. Strings come with their own Methods and Properties that you can make use of. To see which Methods and Properties are available, start a new C# Windows Application. Add a button and a textbox to your form. For the textbox, change the Text property to "some text" (make sure the text is in lowercase). Now Double click your button to get at the coding window. Then enter the following string declaration

string stringVar = textBox1.Text;

On a new line, type the following:

textBox1.Text = stringVar.

As soon as you type the full stop at the end, you'll see the IntelliSense list appear:


IntelliSense is showing you a list of Methods and Properties that are available for this string object you have called stringVar. Here's a fuller list:


There's actually one Property on the list. But it's one you use a lot, and we'll see it in action later.

Most of the Methods on the list you won't use at all, and a lot of them are just plain baffling! Some are quite obvious in what they do, though.

Select ToUpper from the list by double clicking it. Because it's a Method, you need some round brackets. Type a left round bracket and you'll see a yellow box appear, giving you the available options for this Method. For the ToUpper Method, there are only two options available:


You can press the Down arrow on your keyboard to see the other one. But the first one, 1 of 2, is the one we need. As the tool tip is telling you, this Method converts the string to upper case. (The current culture it is talking about is which language you're typing in: a symbolic language like Chinese or Japanese will have different grammatical rules than English.)

The round brackets of the Method are empty, meaning it doesn't take any arguments. So just type the right round bracket, followed by a semicolon to end the line. Your code should look like this:


Now run your programme. When the form starts it will look like this:


After you click the button, C# runs the ToUpper Method and converts the text in the text box to uppercase:


Another Method that changes case is the ToLower Method. This is the opposite of ToUpper, and is used in the same way.

Trim Unwanted Characters in C# .NET



 


If you have another look at the Method list, you'll see that there are three that deal with Trimming: Trim, TrimEnd and TrimStart. These methods can be used to Trim unwanted characters from strings.

Add another button to your form. You can change the Text property of your buttons. Enter the text "Uppercase" for the first one. For the new button, enter Trim for the text property. Add another text box below the first one and set the Text property as follows:

"   Trimming   "

Leave out the double quotes but tap the spacebar on your keyboard three times before you type the text. At the end of the text, tap the spacebar three more times. Your Form should then look like this:


The line in the second text box is where the cursor is.

Now double click your second button to get at the code. We can count the number of characters a string has with the Length property. Enter the following code for your button:


The first line just gets the text from the text box and puts it into a variable called stringTrim. Have a look at the second line, though:

int stringLength = stringTrim.Length;

We've set up a new integer variable called stringLength. To get the length of a string, type a dot after your string variable name. From the IntelliSense list, select the Length property. Note that you don't need any round brackets, because it's a property not a method. The Length of a string, by the way, refers to how many characters is in the string.

The third line uses a MessageBox to display the result:

MessageBox.Show( stringLength.ToString() );

You've seen the ToString method before. This can be used to convert numbers to a string a text. So "10" instead of 10. (The double quotes mean it's text. Without the quotes, it's a number. The variable called stringLength will hold a number.)

Run your programme and click the Trim button on your form. The message box should display an answer of 14. The word "Trimming", however, only has 8 characters in it. The other 6 are the three spaces we put at the beginning and end of the word.

To get rid of space at the beginning and end of text, you can use the Trim method. Add the following line of code to your button:


The code to add is highlighted, in the image above. It's this:

stringTrim = stringTrim.Trim();

So after the dot of the stringTrim variable, you select the Trim method from the IntelliSense list, followed by a pair of empty round brackets. Run your programme and click the button again. You should find that the length is now 8. So Trim has trimmed the blank spaces from the beginning and the end of our word.

If you only wanted to trim the blank spaces at the end of the word, or just the blank spaces at the beginning of the word, you can use TrimEnd and TrimStart:

stringTrim = stringTrim.TrimStart( null );

TrimStart and TrimEnd are supposed to take a character array as a parameter. If you type the keyword null instead, it will trim the white space (blank characters).

Just as a reference for you, here's some code that strips unwanted hyphens off the end of a string:


The trimChar line is a character array ( char[ ] ) with the hyphen in between curly brackets. This is then handed to the TrimEnd method as a parameter.

 

In the next leThe Contains Method in C# .NET



 

The contains method can be used if you want to check if a string contains certain characters. It's fairly simple to use. Here's an example:


After the contains method, you type a pair of round brackets. In between the round brackets, you type the text you're checking for. In our code, we're using an if statement. If it's true that the string contains a "-" character, then some code can be executed.

 

A more complicated, and probably more useful, method that you'll need to know about is calledIndexOf. That's the next lesson.

sson, we'll take a look at the Contains method.

The IndexOf Method in C# .NET



 


The IndexOf method can be used to check if one character is inside of another. For example, suppose you want to check an email address to see if it contains the @ character. If it doesn't you can tell the user that it's an invalid email address.

Add a new button and a new text box to your form. For the Text property of the text box, enter an email address, complete with @ sign. Double click your button to get at the code. Enter the following:


The first thing to examine is how IndexOf works. Here's the line of code:

int result = stringEmail.IndexOf( "@" );

The IndexOf method returns an integer. This number is the character's position in the word you're trying to check. In the code above, we want to check the word that's inside of the variable we've calledstringEmail. We want to see if it contains the "@" character. This goes between the round brackets of IndexOf. If C# finds the character, it will tell you where it was (at position number 3 in the word , for example). This number is then stored inside of the int variable we've called result. If the character you're looking for can't be found, IndexOf will return a value of -1 (minus 1). The IF statement in our code checks the value of the result variable, to see what's inside of it. If it's -1 display an" Invalid Email Address message"; If it's not -1, a different message is displayed.

Run your programme and click the button. Here's the form with an @ character in the text box:


And here's what happens when we delete the @ character from the text box:


Note that the first message box displays "@ found at position 2". If you look at the email address in our text box, however, it's me@me.com. So you might be thinking that the @ character is at position 3, not 2. If C# were to start counting at 1, you'd be right. But it doesn't. When you use the IndexOf method, the count starts at zero.

You can also specify a start position, and a character count for a search. This is useful if you want to do things like checking a longer string and counting how many occurrences there are of a particular character or characters. Or if you want a simple check to see if, say, a website entered in a text box on your form begins with http://www. Here's some code that does just that:


Have a look at this part of the highlighted line:

webAddress.IndexOf( checkWebAddress, start, numOfChars )

This time, we have three parameters inside of the round brackets of IndexOf. The first one is the string we want to check (checkWebAddress). Then we have start, and numOfChars. The start variable is where in your full string (webAddress) you want to start checking. The third parameter, numOfChars, is the number of characters you want to check from that starting position. In our code, the start is 0 and the number of characters is 10.


And finally, for IndexOf, here's some code that checks a long string of text and counts how many times the word true appears:



The code is a bit complex, so don't worry if you don't understand it all. But it's just using IndexOf with three parameters: the word to search for, a starting position, and how many characters you want to check. The start position changes when the word is found; and the number of characters to count shrinks as you move through the word

The Insert Method in C# .NET



 

The Insert method is, not surprisingly, used to insert characters into a string of text. You use it like this:

string someText = "Some Text";

someText = someText.Insert( 5, "More " );

In between the round brackets of Insert, you need two things: A position in your text, and the text you want to insert. A comma separates the two. In our code above, the position that we want to insert the new text is where the T of "Text" currently is. This is the fifth character in the string (the count starts at zero). The text that we want to Insert is the word "More".

 

Exercise
Test out the code above, for the Insert( ) method. Have one message box to display the old text, and a second message box to display the new text.


PadLeft and PadRight



 

The PadLeft and PadRight methods in C# can also be used to insert characters. But these are used to add characters to the beginning and end of your text. As an example, add a new button to your form, and a new text box. For the text box, set the Text property to "Pad Left". Double click your button and enter the following code:

string paddingLeft = textBox5.Text;

paddingLeft = paddingLeft.PadLeft( 20 );

textBox5.Text = paddingLeft;

The PadLeft and PadRight methods can take 1 or two parameters. We're just using 1. This will insert blank space characters to the start of the string. The total number of characters will be 20. So, if you have four characters in the text box, PadLeft(20) will add 16 blank spaces, making a total of 20 characters in the text box after the button is clicked.

Run your programme and test it out. Type the text "Pad Left" in the text box. Your text box should look like this before the button is clicked:


And it will look like this after you click the button:


If you don't want to pad with blank spaces, you can use the second parameter. This is the character you want to pad with:

paddingLeft = paddingLeft.PadLeft(20 , '*');

In the code above, we're telling C# to pad with the asterisk character, instead of the default blank spaces. (Note the use of the single quotes surrounding the * character. C# doesn't seem to like you using double quotes, if the type is char.)

If you change your code to the one above, then click the button on your form, the result will be this:


If you want to add characters to the end of the string, use PadRight instead of PadLeft.

Remove and Replace in C# .NET



 

The Remove Method


As its name suggests, this method is used to Remove characters from a string of text. Here's a simple example of its use:

string oldString = "some text text text";

MessageBox.Show(oldString);

string newString = oldString.Remove(10, 9);

MessageBox.Show(newString);

Remove takes two parameters. The first one is what position in your string you want to start at. (The count starts at zero.) The second parameter is how many characters you want to delete, starting from the position you specified. Add another button to your form and try out the code above.

 

The Replace Method


The Replace method, you won't be surprised to hear, can be used to replace characters in your string. Here's an example of its use:

string spellingError = "mistak";

spellingError = spellingError.Replace(spellingError, "mistake");

The Replace method takes two parameters, the old word and the new word. In the code above, we're replacing "mistak" with "mistake"

Substring in C# .NET



 

The Substring method is used to grab characters from a string of text. For example, suppose you were testing an email address. You want to test the last four characters to see they are .com. You can use Substring to return just those four characters, and see what's in them. (You can also use IndexOf to achieve the same result.)

Substring has this syntax:

the_word.Substring( start_position )

So the word you want to grab characters from goes first, followed by the Substring method. In between the round brackets, you have to tell C# where in the word to start grabbing characters from.

But Substring can also take a second parameter:

the_word.Substring( start_position, num_of_chars_to_grab )

The second parameter is how many characters you want to grab. If you leave this out, C# will grab all the characters to the end of your word. Here's some code to try, with a new button:


We're using Substring with two parameters (5, 4). But since we're grabbing to the end of the word, we could have left out the , 4 at the end.

To test it out, change the me@me.com to me@me.con. Run your programme and you should see "Bad Email Address". Change it back and the email address will be OK.

 

Exercise M
Use Substring to check that an email address ends in .co.uk. For the email address to check, use enquiry@me.co.uk.


Split and Join in C# .NET



 

The Split Method


The Split method is used to split a string of text and put the words into an array. For example, you could grab a line of text from a text file. Each position in the array would then hold a word from the line of text. An example may clear things up.

Add another button to your form. Double click the button to get at the code, and add the following:


Run the programme and click your button. You should see each word from the line of text display.

In the first line of the code, we're setting up a string with three items in it. Each item is separated by a comma. (Comma separated files from software like Excel are quite common, and so too is parsing each line of text.)

For the second line, we have this:

string[] wordArray = lineOfText.Split( ',' );

The first part sets up a string array that we've called wordArray. After the equals sign, we have this:

lineOfText.Split( ',' );

The variable called lineOfText is obviously the line of text we want to examine. For the round brackets of Split, we've typed a comma surrounded by single quotes. That's because C# needs to know what character in your line of text you are using to separate the words. This is known as the delimiter. If our line of text were this instead:

string lineOfText = "item1 item2 item3";

we'd use a blank space as a delimiter. Like this:

string[] wordArray = lineOfText.Split( ' ' );

This time, we've typed a blank space between the single quotes.

But C# will split the line, and put each part into the array we've set up. (It won't include the delimiter.) For our line of text we only have three words. So the Message box in our code displays what is at position 0, position 1, and position 2 in our array.

If you don't know how many position there are in the array (if you have lines of text that vary in size, for example), the you can loop through each position:


foreach (string s in wordArray)
{

MessageBox.Show( s );

}

The Split method can take other parameters, and get a bit complex. So we'll leave it there in this beginners book!

 

The Join Method


You can join the pieces of your arrays back together again. Join, however, is not a method available to ordinary strings. Instead, you can access it through the String class. Like this:


In the code above, we've used Split to split the line of text and put the words into an array. We've then used Join to create a single line of text again. This time, though, the words are separated with hyphens and not commas.

To use Join, first type the word String (with a capital letter). After a dot, you should then see the Join method appear on the IntelliSense list. In between the round brackets of Join, you first need the character your want to use as a delimiter. Note that this is surrounded by double quotes. If you use single quotes, C# will think it is the char variable type. But you need to use the string variable type, so you'll get an error. After a comma, you type the name of the array you want to Join together

A C# .NET Hangman Game



 

To put all our C# string theory into practice, we've developed a simple word-guessing game, popularly known as hangman in the UK. The project is amongst the download files for this course. Look for the folder called Hangman. Inside of this, you'll find a hangman.vbproj. Open up this project in your C# .NET software. Run the programme and you should see this:


After clicking the New Word button, you click on letters of the alphabet. If the word contains the letter you clicked on, it appears in the word. If you guess incorrectly then you lose a life. The game is over when you either guess the word, or run out of lives.

Our version contains words of only three letters, so that you can see what's going on. There are also message boxes, used to display the words. This is for testing purposes.

Open up the code for the project and you'll see that it is heavily commented. We won't go through the code step-by-step here, but examine the code and the comments for yourself. Pay particular attention to these C# string methods:

IndexOf
Insert
Remove
Substring
ToUpper

If you are unsure about any of them, go back a few pages and look at the explanation in this book.

As you're going through the code, though, bear in mind that what the programme is trying to do is manipulate strings and characters, using as many inbuilt C# methods as possible. This is the kind of manipulation that you need to be able to do in your own programming.

Once you've got a good idea of how the programme works, try this exercise.


Exercise
The game only uses words of three letters, at the moment. There are ten words in all. Amend the code to use words of nine letters. You can, of course, use your own. But here's 10 nine letter words for you, if you're stuck. They are all countries:


Argentina
Australia
Greenland
Guatemala
Indonesia
Lithuania
Macedonia
Mauritius
Nicaragua
Venezuela

For this exercise, it's not just a question of changing the words in the array. Can you see what else you need to change?

C# .NET Events



 

In programming terms, an Event is when something special happens. Inbuilt code gets activated when the event happens. The event is then said to be "Handled". The Events that we'll discuss in this section are called GUI Events (GUI stand for Graphic User Interface). They are things like clicking a mouse button, leaving a text box, right clicking, and many more. We'll start with the Click event of buttons.

 

The Click Event for Buttons


The click event gets activated when a button is clicked on. Examine the default code for a button:

private void button1_Click(object sender, EventArgs e)
{

}

In between the round brackets, we have this:

object sender, EventArgs e

The object keyword refers to the object which activated the event, a button in this case. This is being placed in a variable called sender. You can test this for yourself.

Start a new project. Add a button to your new form and double click it. Place the following code between the curly brackets:

MessageBox.Show( sender.ToString() );

We're just using the ToString method on the sender variable. Run your programme and click the button. You should see this:


The Message is displaying which object was the sender of the event, as well as displaying the Text property of the sender: the button with the Text "button1".

The other argument in between the round brackets was this:

EventArgs e

EventArgs is a class. It's short for event arguments, and tells you which events was raised. The letter "e" sets up a variable to use this class. If you change your line of code to this:

MessageBox.Show( e.ToString() );

the message box will then display the following:


So clicking raises a Mouse Event Argument. C# .NET already knows what to do with an event of this kind, so you don't need to write any special code yourself. But what if you wanted to know which button was clicked, the left button or the right?

The MouseDown Event in C# .NET



 

You can see what event are available for a particular control in the Properties area.

In Design View, click on your Form1 to select it, instead of the button. To see what events are available for the Form itself, click the lightning bolt at the top of the Properties area, as in the image below:


When you click the lightning bolt, you'll see a list of events appear:


You've already met the Load event, so we won't cover it here. But notice how many events there are.

Locate the MouseDown event on the list. Now double click the word "MouseDown". You should see a code stub appear:


In between the round brackets, there is still a sender object. But notice the new argument:

MouseEventArgs e

The letter "e" is the default variable name. The type of variable belongs to the MouseEventArgs. You can see what this does by typing the letter "e", then a full stop (period). You should see the IntelliSense list appear:


The list is displaying the properties and methods available to the e variable. One of these is the Button property.

We can use an if statement to check which mouse button was clicked. Add this to your code:


Run your programme and click either of your mouse buttons on the form. You should see a message box display.

 

 

No comments:

Post a Comment