Practicals
Practicals
PRACTICAL 1
2025
1
At the end this practical you should be able…
2
What are we going to do?
3
Creating New Windows Forms Application
– Create a new project
– Search for Windows Forms App in the search bar
– Use the Windows Forms App (.NET Framework)
– Ensure it is for C#
4
Configure Project
– Provide a proper name using you student number:
uXXXXXXXX_INF154_Practical_1
– Select your K drive to store the project on your personal
university drive (Ignore the error on image)
5
Getting Started
– Ensure you have the Toolbox and Solution Explorer Views.
If it is not displayed, then you can add them from the View
Menu.
– If not already open (Form1.cs [Design], you can double click
the Form1.cs file from the solution explorer.
6
Getting Started Continued
– Using the Toolbox, you can drag and drop the required
controls to design you Graphical User Interface (GUI)
– In the example screen below we dragged a button, label
and panel unto the Form1 screen.
7
Getting Started Continued
– IMPORTANT!!! – Every control (button, label, panel, etc.)
added to your screen must first be given a proper name
before you proceed.
– Change the name of the control by updating the Name
property of the control in the properties view.
8
Getting Started Continued
– IMPORTANT!!! – Do not confuse the Text property with the
Name property. The text property is used to update the
content of the control.
– The Text (content) is what will be displayed on the screen.
9
Getting Started Continued
– IMPORTANT!!! – It is very important to provide a meaning
name for the control as this will ensure we do not get
confused with the different controls.
– The name is used to link the back-end code with the front-
end control. The name must be exactly the same..
10
Naming Conventions
The name of your controls cannot contain a lower-case therefore, we use
the camel case naming style where it starts with a lower-case (typically the
abbreviation of the control) and each new word starts with a capital letter
as shown in the examples below.
Button:
Use abbreviation btn
Example – btnMyButton
Label:
Use abbreviation lbl
Example - lblMyLabel
Panel:
Use abbreviation pnl
Example - pnlMyPanel
11
Application: Overview
Objective: The objective is to develop an application that will provide the
highlights of a pong game where 2 goals were score, one from each player at
different times in the game. The application should consist of the following
controls:
– 4 Buttons: – 6 Labels
• Goal 1 • Title
• Goal 2 • Score
• Reset • 4 Spectator Voices
• Close
– 3 Panels
• Player 1 Padel
• Player 2 Padel
• Ball
12
Application: Start –Up
Objective: When the application starts up, it should look something like
the following example. Notice that the “Goal 1” and “Close” buttons are
the only buttons that are enabled while “Goal 2” and “Reset” are disabled:
13
Application: Button “Goal 1” Click
Objective: When the “Goal 1” button is clicked the screen must change as
follows and disable the “Goal 1” button and enable the “Goal 2” button.
Notice the colour, position and text changes for all the different controls on
the screen:
2
14
Application: Button “Goal 2” Click
Objective: When the “Goal 2” button is clicked the screen must change as
follows and disable the “Goal 2” button and enable the “Reset” button.
Notice the colour, position and text changes for all the different controls on
the screen:
3
15
Application: Button “Reset” Click
Objective: When the “Reset” button is clicked the screen must revert back
to the default screen as shown below:
16
Application: Button “Close” Click
Objective: When the “Close” button is clicked the application must close,
similar to what would happen if the X is pressed at the top right corner.
Use the internet to find the necessary code required in C# to close the
application and implement it within the “Close” button click event.
17
Application: Code Snippets
Changing the background colour of the form:
this.BackColor = Color.Blue;
or
frmBackground.ActiveForm.BackColor = Color.Gray;
18
Application: Code Snippets – Example
of the “Goal 1” Button
• Use the following code snippet as a baseline for your application, the
names and values could be different so do not just replicate the code.
Apply the code example to your application to achieve the desired
outcome.
19
Practical 1 Submission
Submit your Practical 1 project on ClickUP as Follows:
–Name your project, “uXXXXXXXX_INF154_Practical_1” (where XXXXXXXX is
your student number) and compress (zip) your project folder (the main
folder that contains your .sln file and all subfolders).
–Submit it under the Practical 1 submission link.
–Once submitted, raise your hand and prepare to present your application
for assessment.
Rubric:
Criteria Mark
Total /10
20
INF 154
PRACTICAL 2
2025
1
At the end this practical you should be able…
1. To work with additional controls such as Combo Boxes,
Numeric up downs , Rich Textbox, List Boxes, Tab
Controls & Radio buttons.
2. To work with variables and constants.
3. To do basic string manipulation.
4. To do basic arithmetic.
2
What are we going to do?
3
Practical Exercise 2a
The practical will involve the basic concept of all programs,
INPUT-PROCESSING-OUTPUT along with the introduction of
variables.
4
Property name:
Practical Exercise 2a txtName
txtAddress
cbxGender Property name:
nudAge btnCapture
The Expected form design Text name:
Capture
Property name:
btnClear
Text name:
Clear
Property name:
rtbOutput
5
Practical Exercise 2a
The Expected Functionality when the Capture button is clicked.
The user’s details will be added in the richtextbox and formatted
as follows.
6
Practical Exercise 2a
The Expected Code for btnCapture
7
Practical Exercise 2a
The Expected Functionality when the Clear button is clicked. The
user’s details and richtextbox information will be cleared.
8
Practical Exercise 2a
The Expected Code for btnClear
9
Practical Exercise 2b
This practical exercise is another example that will involve the
basic concept of INPUT-PROCESSING-OUTPUT along with the
introduction of constants.
10
Practical Exercise 2b
Property name:
txtRadius
The Expected form design Text name:
Radius
Property name:
radCircumference
Text name:
Circumference
Property name:
radArea
Text name:
Area
Property name:
radNone
Text name:
None
11
Practical Exercise 2b
The Expected Functionality when the Circumference radio button
is clicked. The circumference of the circle will be displayed as
shown below.
12
Practical Exercise 2b
The Expected Code for btnCircumference
13
Practical Exercise 2b
The Expected Functionality when the Area radio button is clicked.
The area of the circle will be displayed as shown below.
14
Practical Exercise 2b
The Expected Code for radArea
15
Additional information
1. Create Windows Form Projects
16
Practical Exercise 2c
Try this yourself – This practical serves as the assignment to be assessed for Practical 2
17
Practical Exercise 2c
Part 1:
When the Add button is pressed, this section of the application captures a new word and
adds it to the list box on the left. The word is transferred from one listbox to the other by
selecting it from the list box on the left side and clicking the >> button. This procedure can
also be done in reverse.
18
Practical Exercise 2c
Part 2:
In this part of the program, the user enters the VAT and amount, and depending on which
button is clicked, the program displays either the Gross price or the Net price in a
message box.
Gross Price (Add Vat Button) = Amount + (Amount * Vat/100)
Net Price (Remove Vat) = Amount - (Amount * Vat/100)
When the add vat button is clicked. When the remove vat button is clicked.
19
Practical 2 Submission
20
Practical 2 Rubric
Criteria Mark
Practical submitted with the correct name and format 1
Tab 1 - Can move items from left listbox to right listbox and vice versa 1
Tab 1 – Display appropriate message in MessageBox when moving items from left listbox 1
to right listbox and vice versa.
Tab 2 – Correctly calculated gross price 1
Tab 2 - Correctly calculated net price 1
Tab 2 – Displayed results of the buttons in a MessageBox with appropriate mesage 1
Appropriate naming of all the components 1
Total /10
21
INF 154
PRACTICAL 3
2025
1
At the end this practical you should be able…
2
What are we going to do?
3
Debugging – Getting Started
Debugging is a very useful tool to investigate and analyse
your code. Use debugging to see the implementation of
your code in action. It is helpful in identifying possible
issues with your code.
To get started, ensure you are running the application in
Debug mode and then click on the Start button:
4
Debugging – Add breakpoint
To debug your code, you need to add breakpoints to
indicate from which point onwards you would like to
analyse.
To add a breakpoint, left click on the panel on the left
adjacent to the code where you would like to start
analysing.
5
Debugging – Control Panel
Once a breakpoint has been hit, use the debugging
control panel to Continue, Stop, Step-Into, Step-Over
or Step-Out.
6
Debugging – Remove Breakpoint
To remove a breakpoint, simply left click on the red
dot on the left.
7
Practical Exercise
8
Practical Exercise 3a
Objective: We would like to create a program where the user can calculate
how much they would weigh on the Moon, Mars or Jupiter.
9
Practical Exercise 3a
Key questions:
• Inputs and Obtaining Data:
– How are we obtaining the user’s information?
» With regards to the weight: is it via a textbox or numeric up
down-> What does this mean for the data type?
» How is the user selecting their different options?
– Once I have the interface to obtain the data, do I need to
manipulate it?
• Processing:
– How do I solve the problem?
» What formulas do I need?
» What steps are required?
10
Practical Exercise 3a
Key questions:
• Outputs:
– What type of information is going to be displayed back to the
user?
» Does it have to be manipulated again?
» Must all of it be displayed to the user?
» Is it via a textbox or numeric up down-> What does this
mean for the data type?
11
Practical Exercise 3a
Note:
The algorithm:
This could be more complicated. We
Start could accommodate for any errors
that may occur (alternative steps) and
we could go into more detail about
how we are obtaining the input,
Input
manipulating the data, computing the
process and displaying the final
weight,
selected result.
item
X = weight on Earth /
Earth’s Gravitational
Pull * Celestial Object’s
Gravitational Pull
Output
New Weight
Stop
12
Practical Exercise 3a
13
Practical Exercise 3a
The interface:
Now that we have an understanding of the program we would like to
implement. We can design the interface.
Label
Label
Numeric up down
Group box
Radio button
Label Textbox
14
Practical Exercise 3a
Guideline for setting up your code:
– Declare your variables.
– Get your inputs and deal with data manipulation.
– Processing & Calculations
– Deal with data manipulation and display the results (output).
Example from lecture 3:
15
Practical Exercise 3a
The code:
– Declaring variables:
Note:
– Notice how the variables and constants are not declared within an event
handler. Because we will be using them in all the different event
handlers, we declared global variables and constants. Now we only need
to declare them once.
16
Practical Exercise 3a
The code:
– Get your inputs and deal with data manipulation.
17
Practical Exercise 3a
The code:
– Processing & Calculations.
18
Practical Exercise 3a
The code:
– Deal with data manipulation and display the results (output).
19
Practical Exercise 3b
Objective: We would like to create a program where the user enters two
numbers and selects one of the following options; addition, subtraction,
multiplication, modulus and division. Once two numbers have been
provided and an option has been selected, the result will be displayed. We
would also like to allow the user to clear the results from the interface.
20
Practical Exercise 3b
Key questions:
• Inputs and Obtaining Data:
– How are we obtaining the user’s information?
» With regards to the numbers: is it via a textbox or numeric
up down-> What does this mean for the data type?
» How is the user selecting their different options?
– Once I have the interface to obtain the data, do I need to
manipulate it?
• Processing:
– How do I solve the problem?
» What formulas do I need?
» What steps are required?
21
Practical Exercise 3b
Key questions:
• Outputs:
– What type of information is going to be displayed back to the
user?
» Does it have to be manipulated again?
» Must all of it be displayed to the user?
» Is it via a textbox or numeric up down-> What does this
mean for the data type?
22
Practical Exercise 3b
Note:
The algorithm:
This could be more complicated. We
Start could accommodate for any errors
that may occur (alternative steps) and
we could go into more detail about
how we are obtaining the input,
Input, manipulating the data, computing the
number1,
process and displaying the final
number2,
selected result.
item
X=Number1 (selected
item) Number 2
Output
Result
Stop
23
Practical Exercise 3b
24
Practical Exercise 3b
The interface:
Now that we have an understanding of the program we would like to
implement. We can design the interface.
Numeric up down
Rich text box
Label
Group box
Radio button
Button
25
Practical Exercise 3b
The code:
– Declaring variables:
Note:
– Notice how the variables and constants are not declared within an event
handler. Because we will be using them in all the different event
handlers, we declared global variables and constants. Now we only need
to declare them once.
26
Practical Exercise 3b
The code:
– Get your inputs and deal with data manipulation.
27
Practical Exercise 3b
The code:
– Get your inputs and deal with data manipulation.
28
Practical Exercise 3c
Practical assignment to try at home:
Create a flowchart that calculates a person’s age based on their full date of
birth (DOB). The flowchart should:
– Take the DOB as input.
– Extract the year of birth from the input (see image on next slide).
– Extract the current year from today’s date (see image on next slide).
– Determine the person's age for the current year, regardless of whether
they have already had their birthday.
– Include all necessary steps in the flowchart to correctly calculate the age.
Once the flowchart is complete, test it using your own date of birth to
ensure it produces the correct age.
TIP: You can use draw.io or any other software to do your diagrams.
NB!!! You must add your flowchart within your parent folder
before your zip and submit on ClickUp.
29
Practical Exercise 3c
Next, use your flowchart to develop an Age Calculator app in Windows
Forms. The app must:
– Use a DateTimePicker (dtp) control to capture the date of birth.
– Extract the year of birth from the DateTimePicker’s selected value.
– Extract the current year from today’s date as shown below.
TIP: Remember to give proper names for all your controls and to use the
correct naming conventions.
30
Practical Exercise 3c
The design and label texts should be as follows:
Once the Calculate button is pressed it should display the result as follows:
31
Practical 3 Rubric
Criteria Mark
Flowchart correctly indicated all the steps to calculate one’s age 3
32
Practical 3 Submission
33
INF 154
PRACTICAL 4
2025
1
At the end this practical you should be able…
2
What are we going to do?
3
Controls Naming Convention Table
Control Prefix Example
Description
Name
Form frm frmMain Represents the main window or form.
Button btn btnSubmit Triggers an action when clicked.
Label lbl lblUsername Displays static text or information.
TextBox txt txtUsername Input field for user text entry.
RichTextBox rtxt rtbDescription Multi-line text input with formatting.
CheckBox chk chkSubscribe Represents a binary choice (checked/unchecked).
RadioButton rdo rdoMale Allows selection of one option from a group.
ComboBox cmb cmbCountry Drop-down list for selecting an option.
ListBox lst lstItems Displays a list of selectable items.
DateTimePicker dtp dtpBirthDate Used to pick dates and times.
NumericUpDown nud nudQuantity Allows numeric input with increment/decrement buttons.
Panel pnl pnlContainer Groups related controls together.
4
Controls Naming Convention Table Continued
Control Prefix Example Name Description
TrackBar (Slider) trk trkVolume Used for adjusting a range of values.
ProgressBar prg prgDownload Shows progress of an ongoing operation.
PictureBox pic picProfile Displays an image.
GroupBox grp grpPersonalInfo Groups related controls inside a labeled
box.
TabControl tab tabSettings Allows multiple tabbed pages.
DataGridView dgv dgvEmployees Displays data in a tabular format.
MenuStrip mnu mnuFile Represents the main menu bar.
ToolStrip tls tlsMain A toolbar with buttons and drop-downs.
Timer tmr tmrAutoSave Used to execute actions at set intervals.
OpenFileDialog ofd ofdSelectFile Dialog box for selecting files to open.
SaveFileDialog sfd sfdSaveFile Dialog box for saving files.
FolderBrowserDialog fbd fbdSelectFolder Dialog box for selecting folders.
5
Discussion: Visual Studio Tools and Tips
Keyboard Shortcuts
• Comment/Uncomment code: Ctrl + K, then Ctrl + C (comment) / Ctrl + U
(uncomment)
• Quick Actions & Refactoring: Ctrl + . (suggests fixes like adding using
statements)
• Navigate between open files: Ctrl + Tab
• Format document: Ctrl + K, then Ctrl + D
• Surround with: Ctrl + K, then Ctrl + S
• Rename: Ctrl + R + R
• Run without debugging: Ctrl + F5
Code Snippets for Faster Coding
• prop + Tab + Tab → Creates a property
• for + Tab + Tab → Generates a for loop
• try + Tab + Tab → Generates a try-catch block
6
Discussion: Visual Studio Tools and Tips
Debugging Tricks
• Breakpoints (F9) – Pause execution at a specific line.
• Step Over (F10) – Move to the next line of code without stepping into
functions.
• Step Into (F11) – Enter inside method calls for detailed debugging.
• Immediate Window (Ctrl + Alt + I) – Test expressions while debugging.
7
Practical Exercise 4a
8
Practical Exercise 4a
Expected Screen Design
Create the following form with the appropriate controls. Remember to
name your controls accordingly (e.g for a button you would use btnConvert).
Label
Textbox
Radio buttons
Button
9
Practical Exercise 4a
Error Handling
If the user fails to provide a valid numerical value, the application must
present the following error message.
10
Practical Exercise 4a
Expected Functionality
Once the provided value is valid and the convert button is clicked, and the
pounds radio button is selected, a message box will display the result as
follows.
11
Practical Exercise 4a
Solution
12
Practical Exercise 4b
13
Practical Exercise 4b
Expected Screen Design
Create the following form with the appropriate controls. Remember to
name your controls accordingly (e.g for a button you would use btnDisplay).
Textbox Listbox
Label
Numeric up down
Button 14
Practical Exercise 4b
Expected Functionality
When the Display Data button is clicked, the student’s name and three
grades along with the Total, Percent and Pass status will be displayed on the
RichTextBox.
15
Practical Exercise 4b
Solution
16
Practical Exercise 4b
Solution
17
Practical Exercise 4b
18
Practical Exercise 4c
Take Home Practical Assignment:
Create a C# program that calculates and displays a customer's water bill. The
Customer’s Name and Units Used should be displayed in a RichTextBox
along with the total bill amount the customer must pay at the end of the
month.
Charge rate for Units Used are as follows:
Units Used per Month Charge Rate per Units Used
0 – 200 @ R2.50
201 – 400 @ R5.00
401 – 600 @ R7.50
601 and above @ R10.00
If the total monthly bill exceeds R3000.00 then a supercharge of 14% will be
added on.
For every customer, the minimum monthly bill must be R100.00.
19
Practical Exercise 4c
Background Image
The background image of the form must be the same as the one shown
below:
20
Practical Exercise 4c
Background Image
Here are some screenshots of what the folder structure should look like
after you created the “Asset” folder and saved the water image within the
folder:
21
Practical Exercise 4c
Recommended Controls:
–2 Labels
–2 TextBoxes
–1 RichTextBox
–1 Button
Expected Output: When bill is above R3000.00, super charge is applied
22
Practical Exercise 4c
Expected Output: When bill is below R3000.00 no super charge is applied
23
Practical Exercise 4c
Error Handling
The application should check that both the name and water units' textboxes
have valid values.
Name – Can contain any text value as long as it is not empty.
Water Units – Must be an integer value, remember to use int.TryParse().
Expected Output: When no values are provided:
24
Practical Exercise 4c
Error Handling - Continued
Expected Output: When only name is provided:
25
Practical Exercise 4c
Error Handling - Continued
Expected Output: When both values are provided but Water Units are not a
valid integer value:
TIP: You will need to use a NESTED IF statement where you first check if
both Name and Water Units have a value (don’t forget about the &&, || and
! operators) followed by a NESTED IF to perform the int.TryParse.
26
Practical 4 Rubric
Criteria Mark
Correctly added new folder called “Assets” and saved the water image on ClickUP in the 1
“Assets” folder
Used the correct water image as the forms background image 1
Correctly calculated the bill using the correct rate 2
Correctly implemented and calculated the super charge 1
27
Practical 4 Submission
28
INF 154
PRACTICAL 5
2025
1
At the end this practical you should be able…
2
What are we going to do?
3
Controls Naming Convention Table
Control Prefix Example
Description
Name
Form frm frmMain Represents the main window or form.
Button btn btnSubmit Triggers an action when clicked.
Label lbl lblUsername Displays static text or information.
TextBox txt txtUsername Input field for user text entry.
RichTextBox rtxt rtbDescription Multi-line text input with formatting.
CheckBox chk chkSubscribe Represents a binary choice (checked/unchecked).
RadioButton rdo rdoMale Allows selection of one option from a group.
ComboBox cmb cmbCountry Drop-down list for selecting an option.
ListBox lst lstItems Displays a list of selectable items.
DateTimePicker dtp dtpBirthDate Used to pick dates and times.
NumericUpDown nud nudQuantity Allows numeric input with increment/decrement buttons.
Panel pnl pnlContainer Groups related controls together.
4
Controls Naming Convention Table Continued
Control Prefix Example Name Description
TrackBar (Slider) trk trkVolume Used for adjusting a range of values.
ProgressBar prg prgDownload Shows progress of an ongoing operation.
PictureBox pic picProfile Displays an image.
GroupBox grp grpPersonalInfo Groups related controls inside a labeled
box.
TabControl tab tabSettings Allows multiple tabbed pages.
DataGridView dgv dgvEmployees Displays data in a tabular format.
MenuStrip mnu mnuFile Represents the main menu bar.
ToolStrip tls tlsMain A toolbar with buttons and drop-downs.
Timer tmr tmrAutoSave Used to execute actions at set intervals.
OpenFileDialog ofd ofdSelectFile Dialog box for selecting files to open.
SaveFileDialog sfd sfdSaveFile Dialog box for saving files.
FolderBrowserDialog fbd fbdSelectFolder Dialog box for selecting folders.
5
Discussion: C# Data Type Conversions
What is the difference between the following?
• short x = Convert.ToInt16("1");
• int x = Convert.ToInt32("1");
• long x = Convert.ToInt64("1");
All of the above are of type integer but the main difference is the size or rather
the number of bits used to store the value of the integer which will impact
performance and memory usage.
• Int16 (short) consists of 16 bit (2 bytes) and ranges from: -32,768 – 32,768.
• Int32 (int) consists of 32 bit (4 bytes) and ranges from: -2,147,483,648 –
2,147,483,648.
• Int64 (long) consists of 64 bit (8 bytes) and ranges from: -
9,223,372,036,854,775,808 – 9,223,372,036,854,775,808.
6
Discussion: C# Data Type Conversions
What will be the outcome of the following conversions?
int a = Convert.ToInt32(1,5);
int b = Convert.ToInt32(2,5);
Result:
a=2
b=2
7
Discussion: C# Data Type Conversions
What will be the outcome of the following conversions?
bool a = Convert. ToBoolean(0);
bool b = Convert. ToBoolean(1);
bool c = Convert. ToBoolean(5.1);
Result:
c = false
d = true
E = true
8
Discussion: C# Data Type Conversions
Implicit Versus Explicit Conversion:
Implicit conversion is performed automatically by the compiler and involves
conversions where there is no risk of data loss. The following are examples of
implicit Conversion:
short x = 10;
double y = x;
int z = x;
Explicit conversion is required when converting from a larger type to a smaller type
and involves risk of data loss. The following are examples of explicit conversion:
double a = 9.5;
int b = Convert.ToInt32(a);
string c = Convert.ToString(a);
9
Practical Exercise 5a
10
Practical Exercise 5a
Remember to ask yourself questions:
• Inputs and Obtaining Data:
– Is the user providing us with information, if so, how?
– Once I have the interface to obtain the data, do I need to
manipulate it?
• Processing:
– How do I solve the problem?
» What formulas do I need?
» What steps are required?
• Outputs:
– How are we displaying the information?
– Do we have to manipulate the data again?
11
Practical Exercise 5a
The interface:
Now that we have an understanding of the program we would like to
implement. We can design the interface.
Labels
GroupBox
Textbox
Button
12
Practical Exercise 5a
The code:
– Declaring variables:
13
Practical Exercise 5a
The code:
– Input and process to calculate min and max value of input selection:
14
Practical Exercise 5a
The code:
– Process continued and Output:
15
Practical Exercise 5b
16
Practical Exercise 5b
Remember to ask yourself questions:
• Inputs and Obtaining Data:
– Is the user providing us with information, if so, how?
– Once I have the interface to obtain the data, do I need to
manipulate it?
• Processing:
– How do I solve the problem?
» What formulas do I need?
» What steps are required?
• Outputs:
– How are we displaying the information?
– Do we have to manipulate the data again?
17
Practical Exercise 5b
The interface:
Now that we have an understanding of the program we would like to
implement. We can design the interface.
Labels
Textbox
Button
18
Practical Exercise 5b
The code:
– Declaring variables:
19
Practical Exercise 5c
Practical assignment to try at home:
– You need to create a game where two players compete to see who can throw the
highest number on the dice. The first player to win 3 rounds wins the game.
– The dice roll will be simulated by generating a random number between 1 and 6,
inclusive.
– The value of the dice roll, score and round number must be presented on the
screen
– If both players have the same value, then it is a draw, and no one wins the round.
However, the round is still counted
– You are required to use both if and switch statements in your application. Use the
switch statement to determine if a player has won 3 rounds. You will need to do
this for both players.
– If a player wins the game (won 3 rounds) a MessageBox must indicate which
player has won.
– After a player won the game, all the values must be reset to the initial state in
preparation of the next game.
– P.S: Design you interface exactly as shown in the following images and use the
exact same text/wording in you labels and messages. You will lose marks if it is
not the same
20
Practical Exercise 5c
Startup Screen Layout:
21
Practical Exercise 5c
Example of layout after first round:
Please note that 3 represents the dice value of player one where 4 presents
the dice value of player two, therefore, player 2 won the round as indicated
in the message at the bottom. Also notice that the score has been updated
as well as the round number.
22
Practical Exercise 5c
Example of layout for a draw:
In the case of a draw, the score remains unchanged, but the value of the
dice must be show as can be seen in the image where both players rolled a
6. The round number must also increase even if it is a draw. Also, take note
of the message to be displayed in the result label when it is a draw.
23
Practical Exercise 5c
Example of layout when someone won the game:
Display the winner in a MessageBox with the same message as shown
(adjusted for the winner). Update the score, round number, dice values, and
round result before showing the MessageBox. After clicking OK, reset all
values to their startup screen defaults.
24
Practical 5 Rubric
Criteria Mark
Implemented the same layout and design as shown in the slides. This includes static and 2
dynamic label values.
Used the Random class to generate dice roll values for both players 1
Accurately determined which player won the round 1
Updated the score, player dice, round number and round result labels 1
Correctly handled a draw where the value of the dice are updated, round number and 1
result message but not the score.
Correctly used switch statements to determine if player one or two won the game (won 3 2
rounds). One point for correct implementation per player.
Correctly displayed the results of the game in a MessageBox. 1
Reset the values to the default values after the user click OK on the MessageBox (not 1
before).
Total /10
25
Practical 5 Submission
26
INF 154
PRACTICAL 6
2025
1
At the end this practical you should be able…
2
What are we going to do?
3
Controls Naming Convention Table
Control Prefix Example
Description
Name
Form frm frmMain Represents the main window or form.
Button btn btnSubmit Triggers an action when clicked.
Label lbl lblUsername Displays static text or information.
TextBox txt txtUsername Input field for user text entry.
RichTextBox rtxt rtbDescription Multi-line text input with formatting.
CheckBox chk chkSubscribe Represents a binary choice (checked/unchecked).
RadioButton rdo rdoMale Allows selection of one option from a group.
ComboBox cmb cmbCountry Drop-down list for selecting an option.
ListBox lst lstItems Displays a list of selectable items.
DateTimePicker dtp dtpBirthDate Used to pick dates and times.
NumericUpDown nud nudQuantity Allows numeric input with increment/decrement buttons.
Panel pnl pnlContainer Groups related controls together.
4
Controls Naming Convention Table Continued
Control Prefix Example Name Description
TrackBar (Slider) trk trkVolume Used for adjusting a range of values.
ProgressBar prg prgDownload Shows progress of an ongoing operation.
PictureBox pic picProfile Displays an image.
GroupBox grp grpPersonalInfo Groups related controls inside a labeled
box.
TabControl tab tabSettings Allows multiple tabbed pages.
DataGridView dgv dgvEmployees Displays data in a tabular format.
MenuStrip mnu mnuFile Represents the main menu bar.
ToolStrip tls tlsMain A toolbar with buttons and drop-downs.
Timer tmr tmrAutoSave Used to execute actions at set intervals.
OpenFileDialog ofd ofdSelectFile Dialog box for selecting files to open.
SaveFileDialog sfd sfdSaveFile Dialog box for saving files.
FolderBrowserDialog fbd fbdSelectFolder Dialog box for selecting folders.
5
Discussion: While Loops
Difference between while and do-while.
• while: Condition is checked before the loops executes
(Check before you act).
• Example - Check your schedule before leaving the
house
• do-while: condition is checked after, so the loop executes
at least once (Act first, then check).
• Example - Eat at least once, then decide if you’re still
hungry.
6
Discussion: While Loops
Difference between while and do-while.
• while code example:
while (appointmentToday)
{
GoToOffice();
}
7
Discussion: While Loops
Loop Control Statements:
• Return: Exits the entire method including the loop.
• Break: Exits the entire loop immediately, regardless of the
condition.
8
Discussion: While Loops
Loop Control Statements:
• Continue: Skips the current iteration of the loop and jumps
back to the top of the loop for the next iteration.
9
Discussion: While Loops
Common Mistakes:
• Infinite loop: No break or exit condition. There are cases
where an infinite loop is intentional or required.
10
Discussion: While Loops
Common Mistakes:
• Incorrect or unreachable exit condition
11
Discussion: While Loops
Common Mistakes:
• Declaring variables within the wrong scope:
Wrong scope:
Correct scope:
12
Practical Exercise 6a
Objective: In this practical section, we will be focusing on counter controlled
while loops where you are tasked with creating a windows form program
which will change a gender into a string or character format. The program
should also be able to sort alphabetically in ascending (a – z) and descending
(z – a) order as well as display the count of each gender. This should be
achieved using While Loops & Decision Statements.
13
Practical Exercise 6a
Expected Screen Design
Create the following form with the appropriate controls. Remember to
name your controls accordingly (e.g for a button you would use
btnGenderStats).
14
Practical Exercise 6a
Expected Functionality
– Dynamically populate the list when the form loads.
– When the Sort Ascending/Descending buttons are clicked, the genders
must be sorted accordingly regardless of whether the values are currently
in string or character format.
– When the To String button is clicked, All the gender characters should
change from characters to string formats.
– When the To Character button is clicked, All the gender strings should
change from string to character.
– When same button is clicked multiple times in succession, A single
message box should display as follows.
15
Practical Exercise 6a
Expected Functionality
– When the Gender Statistics button is clicked, A message box showing the
male and female count should be shown.
– Please raise your hand if you do not fully understand any of the code in
the following slides
16
Practical Exercise 6a
Solution - frmPractical6a_Load
17
Practical Exercise 6a
Solution - btnToString_Click
18
Practical Exercise 6a
Solution - btnToCharacter_Click
19
Practical Exercise 6a
Solution - btnGenderStats_Click
20
Practical Exercise 6a
Solution - btnSortAscending_Click
21
Practical Exercise 6a
Solution - btnSortDecending_Click
22
Practical Exercise 6b
23
Practical Exercise 6b
Expected Screen Design
Create the following form with the appropriate controls. Remember to
name your controls accordingly (e.g for a button you would use
btnGenerate).
24
Practical Exercise 6b
Example of Screen After Button Presses
First Button Press Second Button Press
25
Practical Exercise 6b
Solution
26
Practical Exercise 6c
Practical assignment to try at home:
Objective: In this practical section, you are tasked with creating a program
that will generate 10 random grades between 0-100. This program should
be able to:
• compute the average of all the grades.
• tell you how many students passed/failed.
• sort the grades in ascending order.
• sort the grades in descending order.
Please Note. – You are expected to use while loops in your application
wherever applicable. Marks will be deducted if you use a for loop or omit a
loop where it is clearly the most suitable approach.
For example, generating 10 random grades must be done using a loop.
Writing out 10 individual lines of code to generate grades is inefficient and
goes against the programming principles taught in this practical.
27
Practical Exercise 6c
Expected Screen Design
Create the following form with the appropriate controls.
28
Practical Exercise 6c
Expected Functionality
The button “Generate Grades” should populate the list box with 10 random
grades and should range from 0.0 – 100.0 with one decimal point.
HINT: Look into using NextDouble() from the Random class and
Math.Round() to generate a valid grade from 0.0 – 100.0 with one decimal
point.
29
Practical Exercise 6c
Expected Functionality
The “Submit” button must be used to determine which radio button is
selected and perform the specific process. If no radio button is selected, it
must present the user with an appropriate error message in a message box:
30
Practical Exercise 6c
Expected Functionality
When the “Average Grade” radio button is selected and the “Submit”
button is pressed, the application must calculate the average grade from the
list of grades, the outcome must be presented in a message box:
31
Practical Exercise 6c
Expected Functionality
When the “Pass/Fail Grade Count” radio button is selected and the “Submit”
button is pressed, the application must count how many students passed
and how many failed where all marks above 49.9 pass and all marks below
50.0 fail, the outcome must be presented in a message box:
32
Practical Exercise 6c
Expected Functionality
When the “Sort Grades (Ascending)” radio button is selected and the
“Submit” button is pressed, the application must sort all the grades in the
list box from lowest to highest:
HINT: The code sample for practical 6a on slide 22 contains a code example
that may help you understand how to perform the sorting manually. You are
not allowed to use C#’s built-in Sort() method — the sorting must be done
using your own logic.
33
Practical Exercise 6c
Expected Functionality
When the “Sort Grades (Descending)” radio button is selected and the
“Submit” button is pressed, the application must sort all the grades in the
list box from highest to lowest:
HINT: The code sample for practical 6a on slide 22 contains a code example
that may help you understand how to perform the sorting manually. You are
not allowed to use C#’s built-in Sort() method — the sorting must be done
using your own logic.
34
Practical 6 Rubric
Criteria Mark
Generate 10 random grades with while loop. Grades must be to the precision of one 2
decimal point.
Correctly calculated average grade with a while loop and presented in a message box 2
Correctly counted the number of students who passed and failed with a while loop and 2
presented in a message box
Correctly sorted the grades in the list box for both ascending and descending order with 3
while loops.
Correctly determined which radio button is selected when the Submit button is pressed to 1
perform the specific execution and included an error message when no option is selected
that is presented in a message box.
Total /10
35
Practical 6 Submission
36
INF 154
PRACTICAL 7
2025
1
At the end this practical you should be able…
1. To work with for loops.
2. To work with nested for & while loops.
3. To use a timer.
2
What are we going to do?
3
Controls Naming Convention Table
Control Prefix Example
Description
Name
Form frm frmMain Represents the main window or form.
Button btn btnSubmit Triggers an action when clicked.
Label lbl lblUsername Displays static text or information.
TextBox txt txtUsername Input field for user text entry.
RichTextBox rtxt rtbDescription Multi-line text input with formatting.
CheckBox chk chkSubscribe Represents a binary choice (checked/unchecked).
RadioButton rdo rdoMale Allows selection of one option from a group.
ComboBox cmb cmbCountry Drop-down list for selecting an option.
ListBox lst lstItems Displays a list of selectable items.
DateTimePicker dtp dtpBirthDate Used to pick dates and times.
NumericUpDown nud nudQuantity Allows numeric input with increment/decrement buttons.
Panel pnl pnlContainer Groups related controls together.
4
Controls Naming Convention Table Continued
Control Prefix Example Name Description
TrackBar (Slider) trk trkVolume Used for adjusting a range of values.
ProgressBar prg prgDownload Shows progress of an ongoing operation.
PictureBox pic picProfile Displays an image.
GroupBox grp grpPersonalInfo Groups related controls inside a labeled
box.
TabControl tab tabSettings Allows multiple tabbed pages.
DataGridView dgv dgvEmployees Displays data in a tabular format.
MenuStrip mnu mnuFile Represents the main menu bar.
ToolStrip tls tlsMain A toolbar with buttons and drop-downs.
Timer tmr tmrAutoSave Used to execute actions at set intervals.
OpenFileDialog ofd ofdSelectFile Dialog box for selecting files to open.
SaveFileDialog sfd sfdSaveFile Dialog box for saving files.
FolderBrowserDialog fbd fbdSelectFolder Dialog box for selecting folders.
5
Discussion: For Loops
• A for loop is similar to a counter-controlled while loop.
• Use a for loop when you know exactly how many times you
want to repeat a block of code.
• In a for loop, the counter (commonly named i) is controlled
by the loop structure. If you change the value of the
counter inside the loop body, it can cause unexpected
behavior and affect how many times the loop runs.
• A common mistake with for loops is miscalculating the
starting value, condition, or increment. Always test your
loop to make sure it behaves as expected.
• Keywords like return, break, and continue work the same
way in for loops as they do in while loops:
• break exits the loop immediately,
• continue skips to the next iteration,
• return exits the entire method.
6
Discussion: Nested Loops
• A nested loop is simply a loop inside another loop and can consists of any
combination of for and while loops.
• They are often used when you need to repeat something in two dimensions,
like rows and columns in a table or a grid.
• The outer loop runs first, and for each iteration of the outer loop, the inner
loop runs completely.
• Be careful:
• The number of total repetitions can increase quickly. For example, if both
loops run 10 times, the inner code will run 100 times in total.
• Make sure you use different counter names (like i for the outer loop and j
for the inner loop) to avoid confusion.
• Changing the counter of the outer loop from inside the inner loop can cause
unexpected results.
• Just like with single loops, break and continue only affect the loop they are
used in. However, return will exit the entire method, not just the loop. Use
return only when you want to stop all code execution in the method and return
control to the caller.
7
Discussion: Timers
How is a Timer different from a for loop?
• A Timer is like a loop that repeats by itself every few
seconds or milliseconds. Instead of running all the time like
a while loop, it waits a bit, then runs, then waits again, and
so on. It keeps going until you tell it to stop, but it doesn’t
freeze the rest of your program while it runs.
• A for loop executes synchronously and immediately.
• A timer works asynchronously and over time.
Timer accuracy:
• The accuracy of the System.Windows.Forms.Timer runs on
the UI thread and therefore, can experience delays if the UI
is busy.
• For time sensitive applications, using times like
8
Practical Exercise 7a
Objective: We will be creating a timer. The timer can be stopped and the
time can be collected and displayed.
9
Practical Exercise 7a
Remember to ask yourself questions:
• Inputs and Obtaining Data:
– Is the user providing us with information, if so, how?
– Once I have the interface to obtain the data, do I need to
manipulate it?
• Processing:
– How do I solve the problem?
» What formulas do I need?
» What steps are required?
• Outputs:
– How are we displaying the information?
– Do we have to manipulate the data again?
10
Practical Exercise 7a
The interface:
Now that we have an understanding of the program we would like to
implement. We can design the interface.
Label
Label
Rich textbox
Buttons
11
Practical Exercise 7a
The code:
12
Practical Exercise 7a
The code:
13
Practical Exercise 7b
14
Practical Exercise 7b
Remember to ask yourself questions:
• Inputs and Obtaining Data:
– Is the user providing us with information, if so, how?
– Once I have the interface to obtain the data, do I need to
manipulate it?
• Processing:
– How do I solve the problem?
» What formulas do I need?
» What steps are required?
• Outputs:
– How are we displaying the information?
– Do we have to manipulate the data again?
15
Practical Exercise 7b
The interface:
Now that we have an understanding of the program we would like to
implement. We can design the interface.
A label and a numeric up down
Two radio buttons in a group box.
in a group box.
Buttons
16
Practical Exercise 7b
The code:
– Declaring variables, getting your inputs and deal with data manipulation:
17
Practical Exercise 7b
The code:
– Processes – for loop:
18
Practical Exercise 7b
The code:
– Processes – while loop:
19
Practical Exercise 7b
The code:
– Processes –remaining:
20
Practical Exercise 7c
Practical assignment to try at home:
• Create a Windows Forms app that draws a triangle, square, hollow triangle, or
hollow square when the “Draw Shape” button is clicked. Use radio buttons to
select the shape. Validate that a shape is selected and the size is greater than 0.
• Also, simulate a loading spinner using 12 labels, each showing "*", arranged in a
circle-like pattern. Use a timer with an interval of 100 milliseconds. On the first
cycle, make labels 1–12 bold, one by one. On the second cycle, make labels 1–12
regular again, one by one. Repeat this loop until the Start/Stop button is clicked
again.
• Use the timer's Enabled property to check if it's running, so one button can start
or stop it.
• Example to toggle font style:
21
Practical Exercise 7c
Design:
22
Practical Exercise 7c
Validation (Error Handling):
23
Practical Exercise 7c
Triangle: A * followed by four spaces were used per line (row) and an empty
line (row) was used to space the characters.
24
Practical Exercise 7c
Square:
25
Practical Exercise 7c
Hollow Triangle: For the boundary a * and four spaces were used and for the
empty or inner values five spaces were used.
26
Practical Exercise 7c
Hollow Square: It is perfectly fine if the lines are not perfectly aligned, this is
because of the font type and the size allocated to a space for that particular
font. If you want to have them aligned, you can change the font of the
RichTextBox to “Consolas” which is a monospaced font.
27
Practical Exercise 7c
Loading Spinner: The images flow in order from left to right with each image
being anew tick of the timer.
28
Practical 7 Rubric
Criteria Mark
Validate radio button selection and size greater than 0. Present appropriate message in 1
MessageBox.
Draw Triangle based on provided size. 1/2
Draw Square based on provided size. 1/2
Draw Hollow Triangle based on provided size. 2
Draw Hollow Square based on provided size. 2
Timer created with 100ms interval. 1
Start/Stop button correctly starts or stops the timer. 1
Toggle font format between bold and regular for the labels 1-12 with value * for each tick 2
of the timer.
Total /10
29
Practical 7 Submission
30
INF 154
PRACTICAL 8
2025
1
At the end of this practical you should be able to…
2
What are we going to do?
3
Controls Naming Convention Table
Control Prefix Example
Description
Name
Form frm frmMain Represents the main window or form.
Button btn btnSubmit Triggers an action when clicked.
Label lbl lblUsername Displays static text or information.
TextBox txt txtUsername Input field for user text entry.
RichTextBox rtxt rtbDescription Multi-line text input with formatting.
CheckBox chk chkSubscribe Represents a binary choice (checked/unchecked).
RadioButton rdo rdoMale Allows selection of one option from a group.
ComboBox cmb cmbCountry Drop-down list for selecting an option.
ListBox lst lstItems Displays a list of selectable items.
DateTimePicker dtp dtpBirthDate Used to pick dates and times.
NumericUpDown nud nudQuantity Allows numeric input with increment/decrement buttons.
Panel pnl pnlContainer Groups related controls together.
4
Controls Naming Convention Table Continued
Control Prefix Example Name Description
TrackBar (Slider) trk trkVolume Used for adjusting a range of values.
ProgressBar prg prgDownload Shows progress of an ongoing operation.
PictureBox pic picProfile Displays an image.
GroupBox grp grpPersonalInfo Groups related controls inside a labeled
box.
TabControl tab tabSettings Allows multiple tabbed pages.
DataGridView dgv dgvEmployees Displays data in a tabular format.
MenuStrip mnu mnuFile Represents the main menu bar.
ToolStrip tls tlsMain A toolbar with buttons and drop-downs.
Timer tmr tmrAutoSave Used to execute actions at set intervals.
OpenFileDialog ofd ofdSelectFile Dialog box for selecting files to open.
SaveFileDialog sfd sfdSaveFile Dialog box for saving files.
FolderBrowserDialog fbd fbdSelectFolder Dialog box for selecting folders.
5
Discussion: Arrays
Declaring an array:
• Basic declaration with fixed size:
int[] numbers = new int[3];
• Declaration with Initialization (Inline Values):
int[] numbers = new int[] { 10, 20, 30 };
• Shorthand Initialization:
int[] numbers = { 10, 20, 30 };
• Declare First, Assign Later
int[] numbers;
numbers = new int[3];
• Using a Constant or Variable for Size
const int size = 3;
int[] scores = new int[size];
Assigning values:
To assign a value to an element in an array, you need to access that specific
element using the specific index and assigning the value using an equal sign.
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
6
Discussion: Arrays
Looping over an array:
• Always start at index 0, because arrays in C# are zero-based. array[0] is the first
item, not array[1].
• Use array.Length instead of a hardcoded number. This allows your loop to adapt to
any array size, making your code more flexible and error-resistant.
for (int i = 0; i < array.Length; i++)
{
MessageBox.Show(array[i]);
}
• Be careful not to go out of bounds. Accessing an element like array[array.Length]
will cause an index out of range error because indexing starts at 0. To access the
last element, use array.Length - 1.
• A loop can be used not just to read or access array values, but also to assign values.
for (int i = 0; i < numbers.Length; i++)
{
numbers[i] = (i + 1) * 10; // This will assign the values 10, 20, 30, ...
}
• You can also use a reverse loop to access array elements in reverse order:
for (int i = array.Length - 1; i >= 0; i--)
{
MessageBox.Show(array[i]);
}
7
Discussion: ListsBoxes and List Elements
• A ListBox is a GUI control used to display a list of items. You can use it to
show values from an array or collect items entered by the user.
• ListBox items are stored in the .Items collection, which behaves like an
indexed list. The first item is at index 0, just like in an array.
lstNames.Items[0] = "Clark Kent"; // Changes the first item
• You can loop through ListBox items using a for loop and the .Items.Count
property to avoid going out of bounds.
for (int i = 0; i < lstNames.Items.Count; i++)
{
MessageBox.Show(lstNames.Items[i].ToString());
}
• To add items to a ListBox, use .Items.Add(). This adds a new item to the
bottom of the list.
lstNames.Items.Add("Bruce Wayne");
• To remove an item, use .Items.Remove() (by value) or .Items.RemoveAt()
(by index).
lstNames.Items.Remove("Clark Kent"); // Removes by name
lstNames.Items.RemoveAt(0); // Removes first item
8
Discussion: ListsBoxes and List Elements
9
Practical Exercise 8a
Objective: In this practical section, you are tasked with creating a windows
form program which will change the background colour from red to green to
blue every second. The colours should be saved in an array.
10
Practical Exercise 8a
Expected Screen Design
Create the following form with the appropriate controls as shown below.
Remember to name your controls accordingly (e.g for the label you would
use lblHeader).
Label
Listbox
Button
Controls
11
Practical Exercise 8a
Expected Button Functionality
btnShow will be responsible for populating a listbox with the colours in the
–
array.
btnChangeColour will be responsible for starting the timer which will change
–
the background colour of the form every second. As the background colour
changes, the label should also change.
12
Practical Exercise 8a
Solution – btnShow and btnChangeColour
13
Practical Exercise 8a
Solution – tmrChangeColour event handler
14
Practical Exercise 8b
Objective: In this practical section, you are tasked with creating a windows
form program which will use multiple pictures to create a moving picture.
This should be achieved using an Array along with a timer event handler.
15
Practical Exercise 8b
Expected Functionality
Upon startup of the Windows form program (load event), the picture box
–
should cycle through the given list of images from frame01 to frame07 until
the picture box moves from the left to the right of the form.
PictureBox
16
Practical Exercise 8b
Solution: Files
Add an “Assets” folder in your project by right-clicking on your project from
–
17
Practical Exercise 8b
Solution: Files
Once the “Assets” folder has been created, Download, unzip and copy the
–
images into the “Assets” folder. The images can be found on ClickUP in the
“Practicals” ➔ “Week of 19 to 23 May 2025” folder. Once the images have
been copied into the newly created “Assets” folder, right-click the project in
the solutions explorer and add the images to the project using the “Add” ➔
“Existing Item…” option. Navigate to the “Assets” folder and select all the
images. If the images are not appearing, make sure that “All Files” are
selected at the bottom.
18
Practical Exercise 8b
Solution: Files
Once the files are added to the project, you need to update the “Copy to
–
Output Directory” property for each of the image files to either “Copy
Always” or “Copy if newer”. This adds the images and “Assets” folder to the
build process so that it exists in the same directory as the created .exe file.
Also remember to update the “SizeMode” property on the PictureBox so
that the image fits within the frame of the PictureBox.
19
Practical Exercise 8b
Solution – Similar to 8a
20
Practical Exercise 8c
Objective: In this practical section, you are tasked with creating a program
that generates an array when the form loads. Both the size of the array and
the values within it must be randomly generated.
• The array size must be a random number between 5 and 10.
• Each element in the array must be a random temperature value
between 0 and 50.
• The array must be initialised and populated in the Form_Load event.
• The generated values must be displayed in a disabled RichTextBox, with
each line representing a single temperature value.
21
Practical Exercise 8c
22
Practical Exercise 8c
Expected Screen Design and Functionality
Create the following form with the appropriate controls. Remember to
name your controls accordingly (e.g for a button you would use btnDisplay).
This program should use the tabPages control to display the Calculations
and Temperature Readings page. The RichTextBox should be populated
with the random generated temperature values.
23
Practical Exercise 8c
Expected Functionality
Provide a meaningful error when no radio button is selected when the
“Display Result” button is pressed.
24
Practical Exercise 8c
Expected Functionality
When “Average Temperature” is selected and the “Display Result” button
pressed, calculate the average temperature using the temperature values in
the array and present the average in a MessageBox.
25
Practical Exercise 8c
Expected Functionality
When “Second Highest Temperature Reading” is selected and the “Display
Result” button pressed, sort the array in ascending order using a nested for
loop. Present the second highest value in the array in a MessageBox.
Update the RichTextBox to also display the value in ascending order.
26
Practical 8 Rubric
Criteria Mark
Array is created during the Form_Load event with a random size between 5 and 10 2
27
Practical 8 Submission
28
INF 154
PRACTICAL 9
2025
1
At the end this practical you should be able…
1. To manipulate strings.
2. Load text from a file onto a rich text box and save from a
rich text box onto a file.
3. Write your own methods and call them.
4. Add and work with menus.
2
What are we going to do?
– Discussion: Strings and Methods
– Practical 9a: Completed in class.
– Practical 9b: Completed in class.
– Practical 9c: Take home practical.
3
Controls Naming Convention Table
Control Prefix Example
Description
Name
Form frm frmMain Represents the main window or form.
Button btn btnSubmit Triggers an action when clicked.
Label lbl lblUsername Displays static text or information.
TextBox txt txtUsername Input field for user text entry.
RichTextBox rtxt rtbDescription Multi-line text input with formatting.
CheckBox chk chkSubscribe Represents a binary choice (checked/unchecked).
RadioButton rdo rdoMale Allows selection of one option from a group.
ComboBox cmb cmbCountry Drop-down list for selecting an option.
ListBox lst lstItems Displays a list of selectable items.
DateTimePicker dtp dtpBirthDate Used to pick dates and times.
NumericUpDown nud nudQuantity Allows numeric input with increment/decrement buttons.
Panel pnl pnlContainer Groups related controls together.
4
Controls Naming Convention Table Continued
Control Prefix Example Name Description
TrackBar (Slider) trk trkVolume Used for adjusting a range of values.
ProgressBar prg prgDownload Shows progress of an ongoing operation.
PictureBox pic picProfile Displays an image.
GroupBox grp grpPersonalInfo Groups related controls inside a labeled
box.
TabControl tab tabSettings Allows multiple tabbed pages.
DataGridView dgv dgvEmployees Displays data in a tabular format.
MenuStrip/MenuItem mnu mnuFile Represents the main menu bar.
ToolStrip tls tlsMain A toolbar with buttons and drop-downs.
Timer tmr tmrAutoSave Used to execute actions at set intervals.
OpenFileDialog ofd ofdSelectFile Dialog box for selecting files to open.
SaveFileDialog sfd sfdSaveFile Dialog box for saving files.
FolderBrowserDialog fbd fbdSelectFolder Dialog box for selecting folders.
5
Discussion: Strings
Strings in C# are Immutable:
• You can't change a string once it's created.
• Methods like .Replace() or .ToUpper() return a new string:
string original = "hello";
string upper = original.ToUpper(); // original is still "hello“
• Even += creates a new string behind the scenes.
Strings Act Like Character Arrays:
• Like an array, you can access characters in a string using an index:
string myString = “Hello”;
char firstLetter = myString[0];//This will assign the value ‘H’ to firstLetter
• Because strings are immutable, you cannot modify a character of a string:
myString[0] = 'X';//This will not work
• However, there is a workaround to modify characters. Convert the string to
a char array, change it and then convert back to a string:
string myString = "Hello";
char[] chars = myString.ToCharArray();
chars[0] = 'Y';
myString = new string(chars); // "Yello"
6
Discussion: Methods
Method Overloading:
• A custom method cannot have the same name as another method, unless if the
parameter list differs (number, type or order of parameters). All of the
following methods have the same name, yet have different parameter
structures and will therefore, be allowed:
public void Show()
{
//Method code comes here
}
public void Show(string msg)
{
//Method code comes here
}
public void Show(string msg, int times)
{
//Method code comes here
}
• The complier is able to determine which version of the show method you are
trying to use by the provided parameters:
Show(); //Will call the first method from the list above.
Show(“My Message”, 2);//Will call the last method from the list above.
Show(2);//Will give an error as no method with this name and parameter
structure exists. 7
Discussion: Methods
Missing Return statement in Non-Void Methods:
• If your method is supposed to return a value (e.g., int, double), C# requires
a return statement in every possible path:
public int Add(int a, int b, int c)
{
if(a > b)
{
return a + b; //This possible path must return an int
}
}
• Instead, you need to add an else with a return statement to ensure all
possible paths return a value.
public int Add(int a, int b, int c)
{
if(a > b)
{
return a + b; //This possible path must return an int
}
else
{
return c + b;//This possible path must return an int
}
}
8
Practical Exercise 9a
9
Practical Exercise 9a
Remember to ask yourself questions:
• Inputs and Obtaining Data:
– Is the user providing us with information, if so, how?
– Once I have the interface to obtain the data, do I need to
manipulate it?
• Processing:
– How do I solve the problem?
» What formulas do I need?
» What steps are required?
• Outputs:
– How are we displaying the information?
– Do we have to manipulate the data again?
10
Practical Exercise 9a
The interface:
Now that we have an understanding of the program we would like to
implement. We can design the interface.
Text box
Label
Button
11
Practical Exercise 9a
The code:
12
Practical Exercise 9a
The code:
13
Practical Exercise 9a
The code:
14
Practical Exercise 9b
15
Practical Exercise 9b
Remember to ask yourself questions:
• Inputs and Obtaining Data:
– Is the user providing us with information, if so, how?
– Once I have the interface to obtain the data, do I need to
manipulate it?
• Processing:
– How do I solve the problem?
» What formulas do I need?
» What steps are required?
• Outputs:
– How are we displaying the information?
– Do we have to manipulate the data again?
16
Practical Exercise 9b
The interface:
Now that we have an understanding of the program we would like to
implement. We can design the interface. Remember to add SaveFileDialog
and OpenFileDialog controls to be used to save and open files.
Menu items
18
Practical Exercise 9b
The code:
19
Practical Exercise 9b
The code:
20
Practical Exercise 9C
In this assignment, you will load text from a .rtf file named
INF154_Practical_9c.rtf (available on ClickUP under Practicals → Week of 26 to
30 May 2025). The text must be displayed in a RichTextBox, and each word must
be stored in a string array for further processing.
Design:
21
Practical Exercise 9C
Load Button:
• Opens the .rtf file using an OpenFileDialog.
• Loads the file content into a RichTextBox.
• Populates the lines into an array of words.
• You must also include a MenuStrip item named "Load" that triggers the same
event handler as the Load button.
MarsSpeak Button:
• Converts each word in the array to MarsSpeak using the following rules:
• If a word starts with a vowel (A, E, I, O, U), add "way" to the end.
• Example: "Eat" → "Eatway"
• If it starts with a consonant, move the first letter to the end and add "ay".
• Example: "Beat" → "eatBay"
• Display the translated words back in the RichTextBox.
• You may use a method for this functionality (optional).
22
Practical Exercise 9C
Palindrome Button:
• Checks each word in the array to see if it is a palindrome (reads the same
forwards and backwards).
• Examples: "Peep", "Madam"
• If a word is a palindrome, add a * to the end of the word.
• Example: "Peep" → "Peep*"
• Show the updated words in the RichTextBox.
• Also display the total number of palindromes found in a MessageBox.
• You must use a method to check if a word is a palindrome.
• The method should return a bool (true if it is a palindrome, otherwise false).
23
Practical Exercise 9C
Expected Functionality:
24
Practical 9 Rubric
Criteria Mark
Implement the load functionality on both the Load button and Load Menu Item. Includes 4
displaying the text in the .rtf in the RichTextBox and populating a string array with each
line as a new element.
Implement the functionality for the MarsSpeak button. 3
Implemented the functionality for Palindrome button. 3
Total /10
25
Practical 9 Submission
26