Week One
Fundamentals of Programming and
Introduction to Visual C#
The CSC221 Team
[2022|2023]
Main Text for this Course
Title
Starting out with Visual C#
Author
Tony Gaddis
Download for your progressive learning
LECTURE OUTLINE
Introduction To the Visual Studio environment for Visual C#
Variables, Expressions, Formatting Numbers with the ToString Method
Performing Calculations
The use of the following controls
Button
Textbox
Label
Message Box
Friday, January 6, 2023
Preamble
The first step in creating a Visual C# application is creating
the application’s
GUI. You use the Visual Studio Designer, Toolbox, and
Properties window to build the application’s form with the
desired controls and set each control’s properties.
4
The Application’s Form
When you start a new Visual C# project, Visual Studio
automatically creates an empty form and displays it in the
Designer. The Figure on the next slide shows an example.
Think of the empty form as a blank canvas that can be used
to create the application’s user interface.
You can add controls to the form, change the form’s size, and
modify many of its characteristics.
5
Creating a new project in C#
(Based on 2019 version)
Create a Project
Select C# instead of “All Languages”
Look for “Windows Form App…” and click on it
Click Next
Name your project (avoid adding whitespace
in the name)
Check “Place solution and project in the same
directory”
Click “Create”
6
Properties Window
The appearance and other characteristics of a GUI object are
determined by the object’s properties.
When you select an object in the Designer, that object’s properties
are displayed in the Properties window.
Manipulation of the properties of any control on the GUI form is
done via the Properties Window. 7
Hello World Program - GUI Form
In this simple example, we want
to display the “Hello World!”
message after a button is
clicked!
Button
MessageBox
Adding code behind a button
8
Adding code behind the “Display Message” button
Double-click on the button
Add the following code inside the button
click event procedure
MessageBox.Show("Hello World!");
The code above simply displays the “Hello
World!” message via the MessageBox
control.
9
Textbox and Label controls
Textbox and Label controls both display texts on a form.
The texts in a textbox can be changed while
Label controls can be used to display unchanging text, or program
output.
10
Property Function
Name The “variable name” of the textbox control
BackColor The background colour of the component
Font The font of the text within the component
ForeColor The foreground colour of this component, affects the colour of the
text
Text The text within this control
TextAlign Indicates the alignment of text within the control
Enabled If enabled = “false”, then the control cannot be manipulated during
program execution
MultiLine Controls if text can span more than one line
ReadOnly Controls whether the text can be changed or not
Important properties of a Textbox – They can be manipulated via the Properties Window 11
Property Function
Name The “variable name” of the label control
BackColor The background colour of the component
Font The font of the text within the component
ForeColor The foreground colour of this component, affects the colour of
the text
Image The image that will be displayed on the control
ImageAlign The alignment of the image within the control
Text The text within this control
TextAlign Indicates the alignment of text within the control
Enabled If enabled = “false”, then the control cannot be manipulated
during program execution
Important properties of a Label – They can be manipulated via the Properties Window 12
Example 1: Design a Wage Calculator form as shown in the slide 13
Data Sample declaration Sample Usage
Type
int int num_hours num_hours = int.Parse(textBox1.Text);
string string val val = "My book";
double double total_wage = hourly_rate * num_hours;
total_wage
decimal decimal price price = 17.8m;
Another example
int num_hours = int.Parse(textBox1.Text);
price = 17.84980m * Convert.ToDecimal(num_hours);
MessageBox.Show("Price Money = " + price);
float float MessageBox.Show("Price Money = " + 17.84f *
price_money (float)num_hours);
Data Types & Variables in C# 14
Syntax Sample Usage Output
Conversion to int num_hours = int.Parse("18"); num_hours = 18
Integer
Conversion to double total_wage = double.Parse("10.0"); total_wage = 10.0
Double
Conversion to decimal total_wage = decimal.Parse("10.0"); total_wage = 10.0
Decimal
Conversion to float total_wage = float.Parse("10.0"); total_wage = 10
Float
1. It is a must you convert values received from textboxes and labels because
they are string values in their original states.
2. The expression “int num_hours = int.Parse("18.2");” will generate an
error message
Type Conversions to numeric values from a string in C# 15
Format Sample Usage Output Explanation
String
"n" MessageBox.Show(1213.34.ToString("n3")); 1,213.340 Conversion to a
number format, to
3 d.p.
“f” MessageBox.Show(12.497.ToString("f2")); 12.50 Fixed-point
scientific format,
to 2 d.p.
“e” MessageBox.Show(12.347.ToString("e1")); 1.2e+001 Exponential
scientific format,
to 1 d.p.
“e” MessageBox.Show(12.347.ToString("e3")); 1.235e+001 Exponential
scientific format,
to 3 d.p.
Formatting Numbers with the ToString method – some examples (1) 16
Format Sample Usage Output Explanation
String
“e” MessageBox.Show(1234.7.ToString("e3")); 1.235e+003 Exponential
scientific format, to
3 d.p.
“e” MessageBox.Show(1234.7.ToString("e2")); 1.23e+003 Exponential
scientific format, to
2 d.p.
“C” MessageBox.Show(-1234.7.ToString(“c")); ($1,234.70) Currency format, a
negative number
“C” MessageBox.Show(1234.7.ToString(“c")); $1,234.70 Currency format, a
positive number
Formatting Numbers with the ToString method – some examples 17
private void button1_Click(object sender, EventArgs e)
{
double hourly_rate = Double.Parse(textBox2.Text);
//get input from the textbox
int num_hours = int.Parse(textBox1.Text);
double total_wage = hourly_rate * num_hours;
MessageBox.Show("Total wage of worker = " + total_wage);
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
Completing the Wage Calculator Program – Code view 18
1. Get the original price of the item.
2. Get the discount percentage. (For example, 20 is
entered for 20 percent.)
3. Divide the percentage amount by 100 (to move the
decimal point to the correct location).
4. Multiply the percentage by the original price. This is
the amount of the discount.
5. Subtract the discount from the original price. This is
the sale price.
6. Display the sale price (in currency format) in label4.
Example 2: Sale Price Calculator 19
//behind the “Calculate Sale Price” button
private void button1_Click(object sender, EventArgs e)
{
double orig_price = double.Parse(textBox1.Text);
double perct = double.Parse(textBox2.Text);
double discount = orig_price * perct / 100.0;
double new_price = orig_price - discount;
label4.Text = new_price.ToString("c");
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
Source Code for the Sale Price Calculator program 20
Simple Exception Handling
An exception is an unexpected error that happens while a program
is running.
If an exception is not handled by the program, the program will abruptly halt.
Exceptions are usually caused by circumstances that are beyond
the programmer’s control.
For example, suppose the user has entered a value into a TextBox,
and that value is expected to be a number, but the string contains
invalid characters and it cannot be converted. 21
What happens if “12j” is typed into the percentage textbox 22
Handling Exceptions
C#, like most modern programming languages, allows you to
write code that responds to exceptions when they are thrown
and prevents the program from abruptly crashing.
Such code is called an exception handler, and is written with
the try-catch statement
See next slide for a try-catch version of the previous example
23
private void button1_Click(object sender, EventArgs e)
{
try
{
double orig_price = double.Parse(textBox1.Text);
double perct = double.Parse(textBox2.Text);
double discount = orig_price * perct / 100.0;
double new_price = orig_price - discount;
label4.Text = new_price.ToString("c");
}
catch(Exception ex)
{
MessageBox.Show("Invalid data was entered.");
}
}
Code with a try-catch block 24
Output – Effect of the try-catch block 25
Math Class Description Sample Usage Output
Method
Math.Abs(x) Returns the absolute value of x. Math.Abs(-9) 9
Math.Ceiling(x) Returns the least integer that is greater Math.Ceiling(8.2) 9
than or equal to x (a decimal or a double).
Math.Exp(x) Returns . The argument x is a double, and Math.Exp(1.2) 3.3201…
the value that is returned is a double.
Math.Floor(x) Returns the greatest integer that is less Math.Floor(8.2) 8
than or equal to x (a decimal or a double).
Math.Log(x) Returns the natural logarithm of x. The Math.Log(8.2) 2.1041…
argument x is a double, and the value that
is returned is a double.
Using the Math class – Some Examples 26
Math Class Description Sample Usage Output
Method
Math.Log10(x) Returns the base-10 logarithm of x. The Math.Log10(100) 2
argument x is a double, and the value that
is returned is a double.
Math.Max(x, y) Returns the greater of the two values x and Math.Max(3, 8) 8
y.
Math.Min(x, y) Returns the lesser of the two values x and Math.Min(3, 8) 3
y.
Math.Pow(x, y) Returns the value of x (a double) raised to Math.Pow(3, 2) 9
the power of y (also a double). The value
that is returned is a double.
Math.Truncate(x) Returns the integer part of x (a double or a Math.Truncate(3.77) 3
decimal).
Using the Math class – Some Examples (2) 27
The PictureBox Control
A PictureBox control displays a graphic image on a form.
PictureBox controls have properties for controlling the way
the image is displayed.
A PictureBox control can have a Click event handler that
responds when the user clicks the control at run time.
28
The SizeMode property of the PictureBox control can be set to one of the following
values:
Values Description
Normal Normal is the default value. The image will be positioned in the upper-left corner of
the PictureBox control. If the image is too big to fit in the PictureBox control, it will
be clipped.
StretchImage StretchImage resizes the image both horizontally and vertically to fit in the
PictureBox control. If the image is resized more in one direction than the other, it
will appear stretched.
AutoSize With AutoSize, the PictureBox control is automatically resized to fit the size of the
image.
CenterImage CenterImage centers the image in the PictureBox control without resizing it.
Zoom Zoom uniformly resizes the image to fit in the PictureBox without losing its
original aspect ratio. (Aspect ratio is the image’s width to height ratio.) This
causes the image to be resized without appearing stretched.
Modes of displaying an images in a PictureBox control 29
label1
pictureBox1
pictureBox3
pictureBox2 name_label
Example 3: Using the PictureBox to display some statistical figure types 30
Control Name Control Type Property Settings
label1 Label Text: “Click an Image to see its Name”
pictureBox1 PictureBox Image: Select any image on your local machine
BorderStyle: FixedSingle
SizeMode: StretchImage
pictureBox2 PictureBox Same as above
pictureBox3 PictureBox Same as above
name_label Label Text: Blank
Font: “Corbel”, 14pt, style=Bold
This pertains to the code on the next slide: on the design view, each PictureBox
control is double-clicked to fill the appropriate code that will be triggered when the
control is clicked at runtime.
Properties to be set for the controls on the Form on the previous slide 31
private void pictureBox1_Click(object sender, EventArgs e)
{
name_label.Text = "Pie Chart"; //comment
}
private void pictureBox2_Click(object sender, EventArgs e)
{
name_label.Text = "Bar Chart"; //comment
}
private void pictureBox3_Click(object sender, EventArgs e)
{
name_label.Text = "Box-and-Whisker Plot"; //comment
}
//comment = Replace with the right description of the image you used
Code 32
Review Questions
Question 1
Look at the following list of some famous books and their authors.
Books Author
1. Gone with the Wind Margaret Mitchell
2. Roots Alex Haley
3. Atlas Shrugged Ayn Rand
Create an application that gives the authors’ name for a particular book.
The form should have three labels, one for each book.
When the user clicks a button, the application should display the name of its author
in another Label control.
Question 2
The cost of fencing a field depends upon its perimeter. Assuming that you
need to calculate the cost of fencing a rectangular field, it can be calculated
as:
Create an application that allows the user to enter a field’s length and width,
and unit cost of fencing.
The application should have buttons that display the following:
Area of the field
Perimeter of the field
Cost of fencing the field 35
Question 3
A contractor installs slides in children’s parks. Create an
application that allows him to enter the rise of the slide from
the ground, and its inclination with the ground.
The application should display the length of the slide required.
The length of the slide could be calculated as:
36
Create an application with a form that resembles
the figure in the slide. The PictureBox controls
display the images of four fruits (a banana, an
apple, an orange, and a pear) and each fruit’s
calories.
When the application starts, the total calories
displayed should be zero. Each time the user clicks
one of the PictureBoxes, the calories for that fruit
should be added to the total calories, and the total
calories should be displayed.
When the user clicks the Reset button, the total
calories should be reset to zero.
Question 4 37
There are three seating categories at an athletic
stadium. For a baseball game, Class A seats cost
$15 each, Class B seats cost $12 each, and
Class C seats cost $9 each.
Create an application that allows the user to
enter the number of tickets sold for each class.
The application should be able to display the
amount of income generated from each class of
ticket sales and the total revenue generated.
The application’s form should resemble the one
shown in the slide.
Question 5 38
Ticket Sales Revenue
Class A: 320 Class A: $4,800.00
Class B: 570 Class B: $6,840.00
Class C: 890 Class C: $8,010.00
Total Revenue: $19,650.00 – End of Set 1
Class A: 500 Class A: $7,500.00
Class B: 750 Class B: $9,000.00
Class C: 1,200 Class C: $10,800.00
Total Revenue: $27,300.00 – End of Set 2
Class A: 100 Class A: $1,500.00
Class B: 300 Class B: $3,600.00
Class C: 500 Class C: $4,500.00
Total Revenue: $9,600.00 – End of Set 3
Question 5 Cont’d – Test your application with the following sets of test data 39