Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

Create Software components

using C#

Unit CAG 206

WorkBook 1
Using C# to create forms

Tasks 1 – 9:
 Using a Text Box for Input
 Creating a MessageBox
 Buttons and Icons
 Variables
 Concatenation of strings
 Naming conventions

Version: Dec. 2016, v2


NOTE:

You should ensure that you have completed the first exercise: “Introduction to C#
Forms”.

This explains the basics of the C# environment within Visual Studio, how you
should save your projects, how to run the program, and how to view the code.

TASK

1. Open a new C# Windows Form Application

2. Save it to your personal location as


“firstProg”.

Notice the Solution Explorer on the right side of your screen. (If you can't see
it, click this command from the View menu).

Notice the Properties, the References and the Program.cs file within this
section. Double click the Program.cs file to open it, and you'll see some
familiar code:

The Main Method is the entry point for your programme.

The code between the curly brackets of Main will get executed when the
programme first starts. The last line in the WindowsApplication1 code above is
the one that Runs Form1 when the Application starts.

Program.cs in the Solution Explorer on the right is where the code for Main
lives.

SM (content based on: http://www.homeandlearn.co.uk/csharp) Page 2


But we won't be writing code in the Program.cs file, so we can close it.

Click the Program.cs tab.


Click on the cross to close
it. You should now see
your form again.

To see the window where you'll write most of your code, right click Form1.cs in
the Solution Explorer (or use View menu):

The menu has options for View Code and View Designer. The Designer is the
Form you can see at the moment. Click View Code from the menu to see the
following window appear (you can also press the F7 key on your keyboard):

SM (content based on: http://www.homeandlearn.co.uk/csharp) Page 3


This is the code for
the Form itself.

This is the Form:

The code has a lot of ‘using’ statements. They just mean "using some code that's
already been written".

The code also says ‘partial class Form1’. It's partial because some code is hidden
from you. To see the rest of it (which we don't need to alter), click the plus symbol
next to Form1.cs in the Solution Explorer:

Now double click Form1.Designer.cs. You'll see the


following code:

SM (content based on: http://www.homeandlearn.co.uk/csharp) Page 4


Again, you see partial
class Form1, which is the
rest of the code.

Click the plus symbol


next to Windows Form
Designer generated
code (to the left hand
side of the code).You'll
see the following:

InitializeComponent is code (a Method) that is automatically generated for you


when you create a new Windows Application project. As you add things like
buttons and text boxes to your form, more code will be added here for you.

But you don't need to do anything in this window, so you can right click the
Form1.Designer.cs tab at the top, and click Close from the menu.

Click back on the Form1.cs tab at the top to see your form again. If the tab is not
there, right click Form1.cs in the Solution Explorer on the right. From the menu,
select View Designer. Here's what you should be looking at:

It's in Designer view that we'll be adding things like


buttons and text boxes to our form. But you can run this
programme as it is.

From the Debug menu at the top, click Start (Or you can
just press the F5 key on your keyboard.):

SM (content based on: http://www.homeandlearn.co.uk/csharp) Page 5


When you click Start, Visual C# will build the
programme first, and then run it, if it can. If it can't
run your programme you'll see error messages.

But you should see your form running on top of Visual


Studio. It will have its own red X control, and its own
minimize and maximize buttons. Click the red X to
close your programme, and to return to Visual C#.

From now on, when we say Run your programme,


this is what we mean: either press F5, Start, or click
Debug > Start Debugging.

Saving your work in C# .NET

When you save your work, C# will create quite


a few folders and files for you. Click File from
the menu bar at the top of the Visual C#
software, then Save All:

When you click Save All, you'll see the


following dialogue box appear:

NOTE:

1. Always enter a meaningful name into the Name box,


2. Check the Location box – is the project saving to your personal space (eg.
memory stick, server space); if not, click Browse and access it

SM (content based on: http://www.homeandlearn.co.uk/csharp) Page 6


Task 1

1. Double click “Form1.cs” from the Solution


Explorer panel. (you should now be looking at
your form in Designer view).

2. From the toolbox, double click the button


item so that it appears within the form.

3. Change Text property to "A Message".

4. Change size to 75, 23 (width, height).

5. Change size again to 100,30.

You can also move a button by changing its Location property.

6. Use the Properties Window to change the Location of your button to a position
on the form of 100, 50. (100 means 100 units from the left edge of the form; 50
means 50 units down from the top of the form.)

7. A Form also has lots of Properties. Click away from the button and on to the
Form itself. The Properties for the form will appear in the Properties Window.
Change the Text Property of the Form to A First Message.

8. The Form, like the button, also has a Size Property. Change the Size of the Form
to 300, 200.

When you changed the Text property of the Form, you changed the text that runs
across the blue bar at the top, the text in white. You can type anything you like
here, but it should be something that describes what the form is all about or what
it does. Often, you'll see the name of the software here, like Microsoft Word, or
Microsoft Visual C# 2010 Express Edition.

We can now move on to some code.

Task 2
What we want to do now is to display a message box whenever the button is
clicked. So we need the coding window.

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

SM (content based on: http://www.homeandlearn.co.uk/csharp) Page 7


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.

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.

2. Between the 2 curly brackets type:

MessageBox.Show("My First Message");

3. Now click Start (or press F5)/

Task 3

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:

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

SM (content based on: http://www.homeandlearn.co.uk/csharp) Page 8


Type the following:

, "Message"

Again, you need the double quotes. Make sure you include the comma just
before it. Your line of code should look like this:

2. When your line of code looks like the one above, run your programme again.

3. Click your button and you should see a Title


on your Message Box:

Task 4

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.

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

SM (content based on: http://www.homeandlearn.co.uk/csharp) Page 9


2. 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:
3. Double click the one for YesNo,
and it will be added to your code

4. Run your programme again, and


click your button.

Your Message Box will then look like this:

Task 5
Adding Icons to a C# Message Box

Another thing you can add to brighten up your Message Box is an Icon.

1. Type another comma after MessageBoxButtons.YesNo.

2. After the comma, type a capital letter "M" again.

3. From the IntelliSense list that appears, double click MessageBoxIcon.

4. After MessageBoxIcon, type a full stop to see the available icons:

5. Double click ‘Asterisk’ to add it to your code.

6. Run your programme again to see what the icon


looks like on your Message Box:

SM (content based on: http://www.homeandlearn.co.uk/csharp) Page 10


Task 6

Variables in C#
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.
We'll start with something called a String variable.

String Variables in C#

String variables are always text. We'll write a programme that takes text from a
text box, stores the text in a variable, and then displays the text in a message box.

1. If you've got your project open from the previous section, click File from the
menu bar at the top of Visual C#.

2. From the File menu, click Close Solution.

3. Start a new project by clicking File again, then New Project.

4. From the New Project dialogue box, click on Windows Application.

5. For the Name, type String Variables; use your personal location.

6. Click OK, and you'll see a new form appear.

7. Add a button to the form, just like you did in the previous section.

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

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

SM (content based on: http://www.homeandlearn.co.uk/csharp) Page 11


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.

10. To add a Label to the form, move your mouse over to the Toolbox on the
left. Click the Label item under Common Controls:

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

Location: 10, 50
Text: Name

12. Move your mouse back over to the Toolbox.

13. Click on the TextBox entry, then click on your form.

A new Text Box will be added, as in the


following image:

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

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

SM (content based on: http://www.homeandlearn.co.uk/csharp) Page 12


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

string firstName;

17. After the semi-colon, press the enter key on your keyboard to start a new
line.

Naming conventions

The only characters that you can use in your variable names are letters, numbers,
and the underscore character ( _ ). Also, 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.

18. Add the following line to your code (don't forget the semi-colon on the end):

firstName = textBox1.Text;

Remember C# (like most languages) is case sensitive!

SM (content based on: http://www.homeandlearn.co.uk/csharp) Page 13


Task 7

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.

1. Add this line to your code:

MessageBox.Show(firstName);

2. Run your programme again.

3. Type something in your text box, and then click the button. You should see
the text you typed.

Task 8
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 = "James";

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.

1. To try this out, add the following two lines just below your MessageBox line:

firstName = "James";
MessageBox.Show(firstName);

Your coding window will then look like this:

private void btnStrings_Click (object sender,EventArgs e)

string firstName;
firstName = textBox1.Text;
Messagebox.Show(firstName);
firstName = "James";
Messagebox.Show(firstName);
}

SM (content based on: http://www.homeandlearn.co.uk/csharp) Page 14


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 "James".

Task 9

Concatenation in C#

Concatenation is joining things together. You can join direct text with variables, or
join two or more variables to make a longer string.

1. Delete the two new lines you've just added.


2. Now add a second variable, just below the first one:

string messageText;

So you coding window should look like this:

3. 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 person’s name from the text box:

SM (content based on: http://www.homeandlearn.co.uk/csharp) Page 15


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

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

5. Click Save All.

6. Run your programme - Type your first name into


the text box, and then click your button.

You should see something like this:

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.

SM (content based on: http://www.homeandlearn.co.uk/csharp) Page 16

You might also like