Introduction to C# and the Visual Studio IDE

Exercises 1 – Working with Controls

We will now explore a number of the controls in the toolbox which you can use to build a wide variety of GUIs. Each of the controls has its own set of properties, events and methods. Intellisense uses different icons to represent each one:

Event

Method

Property

A method is an action that you can perform on a control. When a method is called it is always followed by parentheses which contain the actual values (arguments) which will be passed to it. If there are no arguments the parentheses will be empty.

Naming Controls

The table lists the prefixes for most of the controls we will use on this course.

Control / Prefix
Check box / chk
Combo box / cbo
Button / btn
Group box / grp
Horizontal scroll bar / hsb
Label / lbl
List box / lst
MenuStrip / mnu
Picture Box / pic
Radio button / rad
Rich text box / rtb
Text box / txt
Timer / tmr

Text Box

Text Boxes are used for entering and displaying character data. The most commonly used property is the Text property. At run time, we can read what a user has entered into a Text Box, by reading the Text property. One of its most commonly used methods is Focus() which positions the cursor inside the text box.

You can make the text box as wide as you like but you cannot change its height. If you change its Font property to a larger point size the height increases as appropriate. If you change its MultiLine property to true (so that the text can go over more than one line), you have complete control over its height. The ScrollBar property adds a scrollbar to a multiline control.

The PasswordChar property of a single line textbox sets the password character to display when the user types text into this text box.

It may be used to display output (as an alternative to a label) by setting the ReadOnly property to true.

The TextAlign property controls the alignment of the text within the textbox.

Program 1.1 Authenticator

Specification: Enter a userid, password and comments. The password is obscured with asterisk characters (“*”). The comments field will grow to make more room for input. Clicking the OK Button will display a message.

1.  Open a new project. Set the form’s text property to Account Information.

2.  On the form place 3 labels, 4 text boxes and two buttons as shown in the figure below.

3.  Set the properties of these controls as listed in the table below.

Control / Property / Property Setting /
Label / Text / Username
Label / Text / Password
Label / Text / Comments
Text box / Name
TabIndex / txtUserName
1
Text box / Name
TabIndex
PasswordChar
TextAlign / txtPassword
2
*
Center
Text box / Name
TabIndex
MultiLine
ScollBars / txtComments
3
True
Vertical
Button / Name
TabIndex / btnOK
4
Button / Name
TabStop / btnCancel
False
TextBox / Name
Readonly / txtMessage
true

Setting the TabIndex specifies the order that controls will receive focus within the form when the user presses the tab button. If the TabStop property is set the false, the user cannot use the tab key to give focus to a control.

Since the labels will not be referred to in any code we write we will not change their default names.

4.  Double click the OK button to bring up the template for the Click event method. Complete the code by adding the following code between the curly braces. This will output a message in the text box:

txtMessage.Text = "You clicked OK";

5.  Run the program and enter text into the text fields. Tab through the controls. It should tab in the sequence specified by the TabIndex property and the Cancel button should be ignored.

end of program 1.1

Amendments to Program 1.1

Experiment with the Wordwrap property of txtComments.

List Box

A list box control displays a list of string items in a box. It provides a number of facilities including the ability to select an item in a list by clicking on it, add items and delete items. The following are the properties and methods of the list box that you will commonly use:

Properties

Items / Contains all of the items in the list box. Each item is indexed. The first item is indexed as 0, the next 1 and so on.
Items.Count / Contains the number of items in the list box.
SelectedIndex / Contain the index or number of the item currently selected. For example, if the 6th item is selected it will have the value of 5 (since the first item is numbered as 0). If no item is selected its value is -1.
Sorted / Has a value of either true of false and specifies whether or not the items are sorted for display.
Text / Contains the currently selected item from the list box.

Methods

Items.Add / Adds an item to the list box.
Items.Clear / Removes all items from the list box.
Items.RemoveAt / Removes an item from the list box. We must supply the index value of the item to be removed.

Program 1.2 A list box of countries

Specification: Allow the user to enter the name of a country into a text box. Provide three buttons to add the name to a list box and to display all of the names alphabetically, to delete a selected country and to delete all of the countries.

1.  Open a new project. Sets the form’s text property to Using a List Box.

2.  On the form place a label, three buttons, a list box and a text box onto the form and position them as shown below.

3.  Set the properties of these controls as listed in the table below. The purpose of the Items property in design mode is to populate the list box before the program starts. To do this click the ellipsis button in the Items property and type the three countries listed into the String Collection Editor.

Control / Property / Property Setting /
Label / Text / Enter name of country
Text box / Name
Text / txtCountryt
blank (i.e. delete Text1)
Button / Name
Text / btnAdd
Add
Button / Name
Text / btnDelete
Delete
Button / Name
Text / btnClear
Clear
List box / Name
Sorted
Items / lstCountries
true
Germany
France
Japan

Coding

A lot of the code from now on will contain comments. These help other programmers (and sometimes yourself!) to understand the code that has been written. The compiler will ignore anything on a line after two forward slashes.

4.  Double click the Add button to bring up the template for the Click event method. Complete the code by adding the following code between the curly braces. The Items.Add method is used to add an item to the list box. Whatever the user has typed into the text box will be added as a new item in the list box.

lstCountries.Items.Add(txtCountry.Text);//add contents of text

//box to list box display

txtCountry.Text = ""; //clear the text box

txtCountry.Focus(); //put cursor in text box ready for the next

//country

5.  Double click the Delete button and add the lines of code below. The Items.RemoveAt method is used to delete the item currently selected. The property SelectedIndex holds the index value of this item. If the third item is selected it holds the value 2 because indexing starts from 0.

//delete selected item from list of displayed items

lstCountries.Items.RemoveAt(lstCountries.SelectedIndex);

6.  Double click the Clear button and add the lines of code below.

//delete all items displayed in the list box

lstCountries.Items.Clear();

end of program 1.2

Enhancements to Program 1.2

1.  AcceptButton form property

Set the form’s AcceptButton property to btnAdd. Run the program. You will now observe that pressing the Enter key will default to the equivalent press on the btnAdd button.

2.  StartPosition form property

Set the form’s StartPosition property to CenterScreen. Run the program. The form will now be centred on the centre of the screen when the program starts. Experiment with some of the other settings.

3.  CancelButton form property

Add a new button to the form. Set its name to btnCancel and its Text property to Cancel. Write the following code for this button’s Click event:

txtCountry.Text = ""

Run the program. Pressing this button will delete any text that is entered in the txtCountry Text Box. The use may want to do this if they have entered some text by mistake.

Set the form’s CancelButton property to btnCancel. Run the program and you will observe that pressing the Escape key will default to the equivalent press on the btnCancel button.

4.  TextAlign property

Experiment with the TextAlign property on any of the button Controls.

Combo Box

The term combo box is short for ‘combination box’ because this control combines the features of the text box and the list box. You use exactly the same properties and methods described earlier for the list box to make a combo box work. A combo box is often called a drop-down list box. The two main differences between list boxes and combo boxes are:

·  With some types of combo box you can edit any of the displayed items or type in an item that is not listed.

·  The standard combo box must be clicked to reveal its items. It therefore takes up less room on the form.

Radio Box

Radio buttons are used to allow the user to select one option from two or more options. Note the following about the radio button:

Properties / Apart from the Name and Text properties, the most useful property is Checked. It holds true if the radio button is selected or false if it is not selected. We will look at this property in more detail when we study the if statement.
Methods / You are not likely to use any of these.
Events / The Click and the CheckChanged events are the ones most often used. The Click event occurs when you click the button and the CheckChanged event occurs when you check or uncheck it. CheckChanged is the dfefault event, i.e. this will be the template that is generated when you double click on a radio button in the form designer.

Check box

The check box is similar to the radio button in that you can test its Checked property to see if it is selected. Unlike the radio button you can select more than one at a time. The check box has similar properties and methods to the radio button.

Group box

The group box is a rectangular shape in which other controls are usually placed. The advantages of using a group box are:

·  You can reposition all of the controls at design time by moving the group box only.

·  You can show or hide all of the controls inside it a run time by showing or hiding the group box only.

·  If you want two or more groups of radio buttons, so that one can be selected from each group, then you must put each group in a group box. Without the group box you could only select one radio button from all of the radio buttons on the form.

You are unlikely ever to use the group box’s methods and events other than the Visible property which can be set to either true or false to hide or display the group box and all of its controls.

Program 1.3 Radio buttons, check boxes and group boxes

Specification: Demonstrate the use of two groups of radio buttons and a group of check boxes.

1.  Open a new project. Sets the form’s text property to Radio Buttons, check boxes and group boxes.

2.  Drag a group box control from the toolbox and position it and size it as shown in the figure below. Change its Text property to Gender.

3.  Place two radio buttons on the group box. Change their names to radMale and radfemale and their Text properties to Male and Female.

4.  Move the group box a little and you will observe that the radio buttons ‘belong’ to it by moving with it

5.  Place a label below the group box. Set its name to lblGender, its Text property to blank, AutoSize to false and BorderStyle to Fixed3D.

6.  Double click the Male radio button to bring up the code template for its default event method. the CheckChanged event. In this simple program it does not matter whether we use the Click or the CheckChanged event. Type in the single line of code below for the label to inform us that the male button has been selected.

lblGender.Text = "You selected Male";

7.  Double click the Female radio button and enter a similar line of code.

lblGender.Text = "You selected Female";

8.  Run the program and try out the two radio buttons.

9.  Place another group box on the form and change its Text property to Age as shown in the figure below.

10.  Place three radio buttons in this group box. Keep the default Names but change their Text properties to those in the figure below:

11.  Run the program to demonstrate that you can select one option from each of the two groups.

12.  Place a third group box on the form and change its Text property to Replies as shown in the figure below.