You are on page 1of 299

Database Creation

Introduction
Before using a database, you must first have one. A database is primarily a
group of computer files that each has a name and a location. Just as there
are different ways to connect to a server, in the same way, there are also
different ways to create a database.

You can create a new database in Microsoft SQL Server Management Studio,
in Microsoft Visual Studio, or on the Command Prompt.

To create a database in Microsoft SQL Server Management Studio, you can


right-click the Databases node and click New Database...

If you are working from Microsoft Visual Studio, to create a new database, in the Server Explorer, you
Connections and click Create New SQL Server Database...
To programmatically create a database, pass the necessary SQL code as the command text of the Sql

private void btnDatabase_Click(object sender, EventArgs e)


{
SqlConnection connection =
new SqlConnection("Data Source=(local);Integrated Security=yes");
SqlCommand command = new SqlCommand(Database Creation Code, connection);

connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
CREATE a DATABASE
The command used to create a database in SQL uses the following formula:

CREATE DATABASE DatabaseName

The CREATE DATABASE (remember that SQL is not case-sensitive, even when you include it i
expression is required. The DatabaseName factor is the name that the new database will carry.

As done in C#, every statement in SQL can be terminated with a semi-colon. Although this is a re
implementations of SQL, in Microsoft SQL Server, you can omit the semi-colon. Otherwise, the above

CREATE DATABASE DatabaseName;

Instead of manually writing all of your code, the Microsoft SQL Server Management Studio provides a
can use and customize. To access the Template Explorer, on the main menu, you can click View ->
Before creating a database, open a new query window. Then:

• To create a new database using sample code, in the Template Explorer, expand the Databases no
Create Database node and drop it in the query window. The new database would be created in th
the current connection
• If you have access to more than one server, to create a database in another server or using a dif
in the Template Explorer, expand the Databases node, right-click Create Database and click Open
Database Engine dialog box, select the appropriate options, and can click OK

With any of these actions, Microsoft SQL Server would generate sample code for you:

-- =============================================
-- Create database template
-- =============================================
USE master
GO

-- Drop the database if it already exists


IF EXISTS (
SELECT name
FROM sys.databases
WHERE name = N'<Database_Name, sysname, Database_Name>'
)

CREATE DATABASE <Database_Name, sysname, Database_Name>


GO

You would then need to edit the code and execute it to create the database. If some sections of this c
to you, we will cover them in subsequent lessons

The Name of a Database


Probably the most important requirement of creating a database is to give it a name. The SQL is v
comes to names. In fact, it is very less restrictive than most other computer languages. Still, there
follow when naming the objects in your databases:

• A name can start with either a letter (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x


F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, or Z), a digit (0, 1, 2, 3, 4, 5, 6, 7, 8, or 9
(_) or a non-readable character. Examples are _n, act, %783, Second
• After the first character (letter, digit, underscore, or symbol), the name can have combinations o
letters, digits, or symbols. Examples are _n24 or act_52_t
• A name can include spaces. Example are c0untries st@ts, govmnt (records), or gl0b# $urve

Because of the flexibility of SQL, it can be difficult to maintain names in a database. Based on this, th
we will use for our objects. In fact, we will adopt the rules used in C/C++, C#, Pascal, Java, an
languages. In our databases:

• Unless stated otherwise (we will mention the exception, for example with variables, tables, etc),
with either a letter (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, A, B, C, D,
L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, or Z) or an underscore
• After the first character, we will use any combination of letters, digits, or underscores
• A name will not start with two underscores
• If the name is a combination of words, at least the second word will start in uppercase. Examples
Statistics, Global Survey, _RealSport, FullName, or DriversLicenseNumber

After creating an object whose name includes space, whenever you use that object, include its nam
Examples are [Countries Statistics], [Global Survey], or [Date of Birth]. Even if you had creat
name that doesn't include space, when using that name, you can still include it in square brac
[UnitedStations], [FullName], [DriversLicenseNumber], and [Country].

Practical Learning: Creating a Database


1. Start Microsoft Visual C# and create a new Windows Application named Exercise3
2. In the Server Explorer, right-click Data Connections and click Create New SQL Server Database..
3. In the Server Name of the Create New SQL Server Database, type (local)
4. In the New Database Name text box, type World Hunger Statistics

5. Click OK (if you receive an error that the database was not created, open the Services in the Adm
check that SQL Server (server name) and SQL Server (MSSQLSERVER) services had started)
6. Design the form as follows:

Control Text Name


Label Database Name:
TextBox txtDatabaseCreate
Button Create btnCreateDatabase

7. Double-click the Create button


8. Implement the Click event of the button as follows:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace Exercise3a
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void btnCreateDatabase_Click(object sender, EventArgs


e)
{
// Make sure the user enters the name of the database
if (txtDatabaseCreate.Text.Length == 0)
{
MessageBox.Show("You must specify the name of " +
"the database you want to create");
txtDatabaseName.Focus();
}

string strConnection =
"Data Source=(local);Integrated Security=yes";

using (SqlConnection connection = new


SqlConnection(strConnection))
{
string strDatabase = txtDatabaseCreate.Text;
SqlCommand command =
new SqlCommand("CREATE DATABASE [" + strDatabase
+ "];",
connection);

connection.Open();

command.ExecuteNonQuery();

MessageBox.Show("A database named \"" +


txtDatabaseName.Text +
"\" has been created on the " +
connection.DataSource + " server.");

txtDatabaseCreate.Text = "";
}
}
}
}
9. Execute the application
10. In the Database text box, type Red Oak High School1
11. Click the Create button
12. Close the form and return to your programming environment

The Location of a Database


As you should be aware already from your experience on using computer, every computer file mu
path is where the file is located in one of the drives of the computer. This allows the operating sys
the file is so that when you or another application calls it, the operating system would not be confused

By default, when you create a new database, Microsoft SQL Server assumed that it wo
Drive:C:\Program Files\Microsoft SQL Server\MSSQL.2\MSSQL\Data folder. If you use the N
box of the SQL Server Management Studio, if you specify the name of the database and click
automatically creates a new file, and appends the .MDF extension to the file: this is the (main) prim
database.

The Primary Size of a Database


When originally creating a database, you may or may not know how many lists, files, or objects the
Still, as a user of computer memory, the database must use a certain portion, at least in the beginn
space that a database is using is referred to as its size. If you use the New Database dialog box i
Server Management Studio, after specifying the name of the database and clicking OK, the inter
specifies that the database would primarily use 2MB. This is enough for a starting database. Of cou
change this default later on or you can increase it when necessary.

If you want to specify a size different from the default, if you are using the New Database to create y
Database Files section and under the Initial Size column, change the size as you wish.

Connecting to a Database
Once a database exists on the server, to use it, as we saw in the previous lesson, you
must first establish a connection to it. We saw that, to programmatically connection to a
Microsoft SQL Server database, you could use a SqlConnection variable. In the
connection string, to specify the database, assign its name to the Database attribute.
Here is an example:

void CreateConnection()
{
SqlConnection connection =
new SqlConnection("Data
Source=(local);Database='Exercise';Integrated Security=yes;");
}

Once you have established a connection, you can then open it and perform the desired actions:

using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Data.SqlClient;

public class Exercise : Form


{
public Exercise()
{
InitializeComponent();
}

void InitializeComponent()
{
SqlConnection connection =
new SqlConnection("Data Source=(local);" +
"Database='Exercise';" +
"Integrated Security=yes;");
SqlCommand command = new SqlCommand(SQL Code, connection);

connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
}

public class Program


{
static int Main()
{
System.Windows.Forms.Application.Run(new Exercise());
return 0;
}
}
Renaming a Database
Database maintenance consists of renaming one database or removing another. To change the n
Transact-SQL provides sp_renamedb. (Notice that the name starts with sp_. This is called a stored
learn how to create them. For now, you can trust that they work and do what they are supposed to do
would be:

EXEC sp_renamedb 'ExistingName', 'NewName'

The EXEC sp_renamedb expression is required. The ExistingName factor is the name of the databa
rename. The NewName factor is the name you want the database to have after renaming it.
Here is an example of renaming a database:

EXEC sp_renamedb 'RentalCars', 'BethesdaCarRental


GO

To rename a table in a C# code, pass the EXEC sp_renamedb code as string to a SqlCommand
SqlCommand.ExecuteNonQuery() method.

Deleting a Database
If you have created a database but don't need it anymore, you can delete it. It is important to know
you create a database, whether using Microsoft SQL Server Management Studio, the Command P
Visual Studio, every database can be access by any of these tools and you can delete any of the dat
these tools.

As done with creating a database, every tool provides its own means.

To delete a database in Microsoft SQL Server Management Studio, locate it in the left frame, rig
Delete:

The Delete Object dialog box would come up. If you still want to delete the database, you can click OK

To delete a database in SQL, you use the DROP DATABASE instruction followed by the name o
formula used is:

DROP DATABASE DatabaseName

Before deleting a database in SQL, you must make sure the database is not being used or accessed
by another object.

If you are in the Microsoft SQL Server Management Studio, you can delete a database using a code te
code, display the Template Explorer. From the Template Explorer, expand the Databases node, th
Database node and drop it in the query window. You can then customize the generated code:

-- =============================================
-- Create database template
-- =============================================
USE master
GO

-- Drop the database if it already exists


IF EXISTS (
SELECT name
FROM sys.databases
WHERE name = N'<Database_Name, sysname, Database_Name>'
)
DROP DATABASE <Database_Name, sysname, Database_Name>
GO
Practical Learning: Deleting a Database
1. To allow the user to delete a database, change the design of the form as follows:

Control Text Name


Label Database Name:
TextBox txtDatabaseCreate
Button Create btnCreateDatabase
Label Database Name:
TextBox txtDatabaseDelete
Button Create btnDeleteDatabase

2. Double-click the Delete button


3. Implement the Click event of the button as follows:

private void btnDeleteDatabase_Click(object sender, EventArgs e)


{
// Make sure the user enters a database
if( txtDeleteDatabase.Text.Length == 0)
{
MessageBox.Show("You must specify the name of " +
"the database you want to delete");
txtDatabaseCreate.Focus();
}
string strConnection =
"Data Source=(local);Integrated Security=yes";

using (SqlConnection connection = new


SqlConnection(strConnection))
{
string strDatabase = txtDeleteDatabase.Text;
SqlCommand command =
new SqlCommand("DROP DATABASE [" + strDatabase +
"];",
connection);

connection.Open();

command.ExecuteNonQuery();

MessageBox.Show("A database named \"" +


txtDeleteDatabase.Text +
"\" has been deleted from the " +
connection.DataSource + " server.");

txtDeleteDatabase.Text = "";
}
}
4. Execute the application
5. In the Database text box, type Red Oak High School1
6. Click the Delete button

7. Click OK
8. Close the form and return to your programming environment

Database Routines
The Current Database
While writing SQL code, you should always know what database you are working on, otherwise you m
wrong database. To programmatically specify the current database, use the USE keyword followed
database. The formula to use is:

USE DatabaseName;

Here is an example:

USE GovernmentStatistics;
Refreshing the List of Databases
Some of the windows that display databases, like the Microsoft SQL Server Management Studio, do
immediately if an operation occurred outside their confinement. For example, if you create a dat
window or in a Windows Application, its name would not be updated in the Object Explorer. To
changes, you can refresh the window that holds the list.

In Microsoft SQL Server Management Studio, to update a list, you can right-click its category in the
click Refresh. Only that category may be refreshed. For example, to refresh the list of databases, in
you can right-click the Databases node and click Refresh.

Microsoft SQL Server Primary Settings


Introduction
When you install Microsoft SQL Server, it also installs 5 databases named master, model, msdb,
databases will be for internal use. This means that you should avoid directly using them, unless you
you are doing.

The System Databases


One of the databases installed with Microsoft SQL Server is named master. This database holds
about the server on which your Microsoft SQL Server is installed. For example, we saw earlier th
operation on the server, you must login. The master database identifies any person, called a use
database, about when and how.

Besides identifying who accesses the system, the master database also keeps track of everything y
including creating and managing databases.

You should not play with the master database; otherwise you may corrupt the system. For exam
database is not functioning right, the system would not work.

A Namespace
As you should know from your learning C#, a namespace is a technique of creating a series of ite
unique name. For example, if you start creating many databases, there is a possibility that you may
databases with the same name. If using a namespace, you can isolate the databases in various names
manage many other aspects of your database server, you use namespaces and you put objects, ot
within those namespaces. Therefore, a namespace and its content can be illustrated as follows:
Notice that there are various types of objects within a namespace.

The Schema of a Database


Within a namespace, you can create objects as you wish. To further control and manage the
namespace, you can put them in sub-groups called schemas. Therefore, a schema is a group
namespace. This also means that, within a namespace, you can have as many schemas as you want:

To manage the schemas in a namespace, you need a way to identify each schema. Based on this,
have a name. In our illustration, one schema is named Schema1. Another schema is named Sch
schema is named Schema_n.

Inside of a schema, two objects cannot have the same name, but an object in one schema can have th
object in another schema. Based on this, if you are accessing an object within its schema, you can s
since that name would be unique. On the other hand, because of the implied possibility of dealin
similar names in your server, when accessing an object outside of its schema, you must qualify it. To
type the name of the schema that contains the object you want to use, followed by the period opera
name of the object you want to use. From our illustration, to access the Something1 object that belon
would type:

Schema1.Something1

There are two types of schemas you can use, those built-in and those you create. When Microsoft SQ
it also creates a few schemas. One of the schemas is called sys.

The sys schema contains a list of some of the objects that exist in your system. One of these objects
(actually, it's a view). When you create a database, its name is entered in the databases object us
you gave it.

The Database Owner


In the previous lesson, we saw that, before using a database, you must establish a connection with
this using a user account that can use the server. Once the connection exists, you can create a da
SQL Server, the user who creates a database is referred to as the database owner. To identify this u
SQL Server is installed, it also creates a special user account named dbo. This account is automatic
permissions on the databases of the server.

Because the dbo account has default access to all databases, to refer to an object of a database, y
typing dbo, followed by the period operator, followed by the name of the object.

The Nullity of a Field

Introduction
During data entry, users of your database

face fields that expect data. Sometimes, for one reason or another, data will
not be available for a particular field. An example would be an MI (middle
initial) field: some people have a middle initial, some others either don't have
it or would not (or cannot) provide it. This aspect can occur for any field of
your table. Therefore, you should think of a way to deal with it.

A field is referred to as null when no data entry has been made to it:

• Saying that a field is null doesn't mean that it contains 0 because 0 is a value
• Saying that a field is null doesn't mean that it is empty. A field being empty could mean
that the user had deleted its content or that the field itself would not accept what the user
was trying to enter into that field, but an empty field can have a value

A field is referred to as null if there is no way of determining the value of its content (in reality,
the computer, that is, the operating system, has its own internal mechanism of verifying the
value of a field) or its value is simply unknown. As you can imagine, it is not a good idea to
have a null field in your table. As a database developer, it is your responsibility to always
know with certainty the value held by each field of your table.

A field is referred to as required if the user must provide a value for it before moving to another
record. In other words, the field cannot be left empty during data entry.

Practical Learning: Introducing Database Records


1. Start Microsoft Visual C#
2. In the Server Explorer, right-click Data Connections and click Add New SQL Server
Database
3. In the Server Name combo box, select the server or type (local)
4. Set the name of the database to CPAR3 and click OK
5. In the Server Explorer, expand server.CPAR3.dbo
6. Under it, right-click Tables and click Add New Table
7. As the caret is blinking in the first empty box under Column Name, type ReceiptNumber
and press Tab
8. Set its data type to int
9. To save the table, on the Standard toolbar, click the Save button
10. Set the name to RepairOrders and click OK
Visually Setting the Nullity of a Field
To solve the problem of null and required fields, Microsoft SQL Server proposes one of two
options: allow or not allow null values on a field. For a typical table, there are pieces of
information that the user should make sure to enter; otherwise, the data entry would not be
validated. To make sure the user always fills out a certain field before moving to the next field,
that is, to require the value, if you are visually creating the table, clear the Allow Nulls check
box for the field. On the other hand, if the value of a field is not particularly important, for
example if you don't intend to involve that value in an algebraic operation, check its Allow Nulls
check box.

Practical Learning: Applying Fields Nullity


1. Under Allow Nulls, in the first check box that corresponds to the ReceiptNumber, click the
check box to clear it
2. Complete the nullity of the fields as follows:

Column Name Data Type Allow Nulls


ReceiptNumber int Unchecked
OrderDate datetime
OrderTime datetime
CustomerName varchar(80) Unchecked
CarMake varchar(50)
CarModel varchar(50) Unchecked
CarYear int Unchecked
ProblemDescription text Unchecked
TotalParts money Unchecked
TotalLabor money Unchecked
TotalOrder money
Recommendations text

3. Save the table

Programmatically Setting the Nullity of a Field


If you are programmatically creating the table using SQL, to specify that a column can allow
null values, type NULL on the right side of the column definition. To specify that the values of
the column are required, on the right side, type NOT NULL. If you do not specify NULL or NOT
NULL, the column will be created as NULL. Here are examples:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace Exercise
{
public partial class Exercise : Form
{
public Exercise()
{
InitializeComponent();
}

private void btnDatabase_Click(object sender, EventArgs e)


{
using (SqlConnection connection =
new SqlConnection("Data Source=(local);" +
"Database='Exercise1';" +
"Integrated Security=yes;"))
{
SqlCommand command =
new SqlCommand("CREATE TABLE Persons( " +
"FirstName varchar(20) NULL, " +
"LastName varchar(20) NOT NULL, " +
"Gender smallint);",
connection);
connection.Open();
command.ExecuteNonQuery();

MessageBox.Show("A new table named Persons has been crated.");


}
}
}
}

If the table was created already and it holds some values, you cannot change its nullity
option.

Introduction
One of the goals of a good table is to be able to uniquely identity each
record. In most cases, the database engine should not confuse two
records

. Consider the following table:


Category Item Name Size Unit Price
Women Long-sleeve jersey dress Large 39.95
Boys Iron-Free Pleated Khaki Pants S 39.95
Men Striped long-sleeve shirt Large 59.60
Women Long-sleeve jersey dress Large 45.95
Girls Shoulder handbag 45.00
Women Continental skirt Petite 39.95

Imagine that you want to change the value of an item named Long-
sleeve jersey dress. Because you must find the item programmatically,
you can start looking for an item with that name.

This table happens to have two items with that name. You may then decide to look for an item using
Category column, there are too many items named Women. In the same way, there are too many
Large value in the Size column, same problem in the Unit Price column. This means that you don't h
you can use to isolate the record whose Item Name is Long-sleeve shirt.

To solve the problem of uniquely identifying a record, you can create a particular column whose
distinguish one record from another. To assist you with this, the SQL allows you to create a column w
integer type but the user does not have to enter data for that column. A value would automatically
field when a new record is created. This type of column is called an identity column.

You cannot create an identity column on an existing table, only on a new table.

Visually Creating an Identity Column


To create an identity column, if you are visually working in the design view of the table, in the top
name of the column. By tradition, the name of this column resembles that of the table but is singular
name of the column ends with _id, Id, or ID.

After specifying the name of the column, set its data type to an integer-based type. Usually, the data
the bottom section, click and expand the Identity Specification property. The first action you sho
(Is Identity) property from No to Yes.
Once you have set the value of the (Is Identity) property to Yes, the first time the user performs da
of the first record would be set to 1. This characteristic is controlled by the Identity Seed proper
count to start to a value other than 1, specify it on this property.

After the (Is Identity) property has been set to Yes, the SQL interpreter would increment the value of
1, which is the default. This means that the first record would have a value of 1, the second would ha
so on. This aspect is controlled by the Identity Increment property. If you want to increment by
can change the value of the Identity Increment property.

Practical Learning: Creating an Identity Column


1. In the top section of the table, click ReceiptNumber
2. In the lower section of the table, expand Identity Specification and double-click (Is Identity) to
3. Click Identity Seed and type 1000

4. Save the table

Creating an Identity Column Using SQL


If you are programmatically creating a column, to indicate that it would be used as an identity colum
data type, type identity followed by parentheses. Between the parentheses, enter the seed value, fo
followed by the increment value. Here is an example:

private void btnDatabase_Click(object sender, EventArgs e)


{
using (SqlConnection connection =
new SqlConnection("Data Source=(local);" +
"Database='Exercise1';" +
"Integrated Security=yes;"))
{
SqlCommand command =
new SqlCommand("CREATE TABLE StoreItems( " +
"StoreItemID int IDENTITY(1, 1) NOT NULL, " +
"Category varchar(50), " +
"[Item Name] varchar(100) NOT NULL, " +
"Size varchar(20), " +
"[Unit Price] money);",
connection);
connection.Open();
command.ExecuteNonQuery();

MessageBox.Show("A new table named StoreItems has been crated.");


}
}

Introduction
Sometimes most records under a certain column may hold the same value
although just a few would be different. For example, if a school is using a
database to register its students, all of them are more likely to be from
the same state. In such a case, you can assist the user by automatically
providing a value for that column. The user would then simply accept the
value and change it only in the rare cases where the value happen to be
different. To assist the user with this common value, you create what is
referred to as a default value.

Visually Creating a Default Value


You can create a default value of a column when creating a table. To specify the default value of a
section, click the column. In the bottom section, click Default Value or Binding, type the desired valu
of the column's data type:

It the Data Type is Intructions


Text-based (char, varchar, text,
Enter the value in single-quotes
and their variants)
Numeric-based Enter the value as a number but following the rules of the
data type.
For example, if you enter a value higher than 255 for a
tinyint, you would receive an error
Enter the date as either MM/DD/YYYY or YYYY/MM/DD.
You can optionally include the date in single-quotes.
Date or Time
Enter the time following the rules set in the Control
Panel (Regional Settings).
Enter the value as 0 for FALSE or any other long integer
Bit
value for TRUE

Programmatically Creating a Default Value


To specify the default value in a SQL statement, when creating the column, before the semi-c
parenthesis of the last column, assign the desired value to the DEFAULT keyword. Here are example

private void btnDatabase_Click(object sender, EventArgs e)


{
using (SqlConnection connection =
new SqlConnection("Data Source=(local);" +
"Database='Exercise1';" +
"Integrated Security=yes;"))
{
SqlCommand command =
new SqlCommand("CREATE TABLE Employees " +
"( " +
"FullName VARCHAR(50), " +
"Address VARCHAR(80), " +
"City VARCHAR(40), " +
"State VARCHAR(40) DEFAULT = 'NSW', " +
"PostalCode VARCHAR(4) DEFAULT = '2000', " +
"Country VARCHAR(20) DEFAULT = 'Australia');",
connection);
connection.Open();
command.ExecuteNonQuery();

MessageBox.Show("A new table named Employees has been created");


}
}

After creating the table, the user does not have to provide a value for a column that has a default.
provide the value, the default would be used when the record is saved.

If the user provides a value for a column that has a default value and then deletes the value, the default v
apply anymore: The field would simply become empty

Introduction
There are various ways you can assist the user with data entry. You can
create an expression using one or a combination of arithmetic and/or SQL
operators. You can create an expression when creating a table.
Visually Creating an Expression
To create an expression when visually creating a table, in the top section,
specify the column's name (only the column name is important). In the
bottom section, expand the Computed Column Specification field and, in its
(Formula) field, enter the desired expression.

Practical Learning: Creating an Expression Column


1. In the top section, click TotalOrder
2. In the bottom section, expand the Computed Column Specification field
3. Click (Formula), type TotalParts + TotalLabor, and press Enter

4. Save the table and close it


5. Open the table to show its data
6. Enter the values of the fields without the total order and move to the next record
7. Close the table

Creating a SQL Expression


You can also programmatically create an expression in a SQL expression you are using to create a tab
placeholder of the column, enter the name of the column, followed by AS, and followed by the desired
an example:

private void btnDatabase_Click(object sender, EventArgs e)


{
using (SqlConnection connection =
new SqlConnection("Data Source=(local);" +
"Database='Exercise1';" +
"Integrated Security=yes;"))
{
SqlCommand command =
new SqlCommand("CREATE TABLE Circle( " +
"CircleID int identity(1,1) NOT NULL, " +
"Radius decimal(8, 3) NOT NULL, " +
"Area AS Radius * Radius * PI());",
connection);
connection.Open();
command.ExecuteNonQuery();

MessageBox.Show("A new table named Circle has been crated.");


}
}
Using an Expression During Data Entry
When performing data entry, you must not provide a value for a column that has an expression;
would provide the value automatically. Here is an example of entering data for the above Circle table:

Introduction
Some operations are difficult or even impossible to obtain with an
expression, or the operation could become too complex to achieve. The
alternative is to create a function that would take care of performing the
operation and supplying the result to the table. Of course, as you may know
already, a function is its own object. This means that, after creating it, to
use its result in a table, you must call it. For example, you can create a
function that returns a value, then call that function and assign its returned
value to a column. You can create your own function and use it, or you can
use one of the built-in functions of Transact-SQL.

Creating and Using a Function


In order to involve a function with your data entry, you must have one. You can create your own
techniques we learned already. To make the function easily accessible, you should create it as part
would use it. Here is an example:

-- =============================================
-- Author: FunctionX
-- Create date: Saturday 22 December 2007
-- Description: Used to calculate the greatest common divisor
-- =============================================
CREATE FUNCTION GCD
(
@a int, @b int
)
RETURNS int
AS
BEGIN
DECLARE @Remainder int;

WHILE @b <> 0
BEGIN
SET @Remainder = @a % @b;
SET @a = @b;
SET @b = @Remainder;
END

RETURN @a
END

When calling the function, follow the normal rules. Here are examples:

INSERT INTO Calculations VALUES(345, 135, dbo.GCD(345, 135));


GO
INSERT INTO Calculations VALUES(40, 6, dbo.GCD(40, 6));
GO
INSERT INTO Calculations VALUES(16, 28, dbo.GCD(16, 28));
GO
Using Built-In Functions
You can use one of the built-in functions of Transact-SQL. Probably the best way to be familiar with t
is to check the online documentation to find out if the assignment you want to perform is already crea
functions would spare you the trouble of creating your own function. For example, imagine you have
AutoRepairShop and imagine it has a table used to create repair orders for customers:

CREATE TABLE RepairOrders


(
RepairID int Identity(1,1) NOT NULL,
CustomerName varchar(50),
CustomerPhone varchar(20),
RepairDate DateTime
);
GO

When performing data entry for this table, you can let the user enter the customer name and pho
other hand, you can assist the user by programmatically entering the current date. To do this,
GETDATE() function. Here are examples:
INSERT INTO RepairOrders(CustomerName, CustomerPhone, RepairDate)
VALUES('Annette Berceau', '301-988-4615', GETDATE());
GO
INSERT INTO RepairOrders(CustomerPhone, CustomerName, RepairDate)
VALUES('(240) 601-3795', 'Paulino Santiago', GETDATE());
GO
INSERT INTO RepairOrders(CustomerName, RepairDate, CustomerPhone)
VALUES('Alicia Katts', GETDATE(), '(301) 527-3095');
GO
INSERT INTO RepairOrders(RepairDate, CustomerPhone, CustomerName)
VALUES(GETDATE(), '703-927-4002', 'Bertrand Nguyen');
GO

You can also involve the function in an operation, then use the result as the value to assign to a field
function that takes one or more arguments; make sure you respect the rules of passing an argumen
calling it.

If none of the Transact-SQL built-in functions satisfies your requirements, you can create your own.

Check Constraints
Introduction
When performing data entry, in some columns, even after indicating the
types of values you expect the user to provide for a certain column, you
may want to restrict a range of values that are allowed. To assist you with
checking whether a newly entered value fits the desired range, Transact-
SQL provides what is referred to as a check constraint.

A check constraint is a Boolean operation performed by the SQL interpreter.


The interpreter examines a value that has just been provided for a column.
If the value is appropriate:

1. The constraint produces TRUE


2. The value gets accepted
3. The value is assigned to the column

If the value is not appropriate:

1. The constraint produces FALSE


2. The value gets rejected
3. The value is not assigned to the column

You create a check constraint at the time you are creating a table.

Visually Creating a Check Constraint


To create a check constraint, when creating a table, right-click anywhere in (even outside) the
table and click Check Constraints...

This would open the Check Constraints dialog box. From that window, you can click Add.
Because a constraint is an object, you must name it. The most important piece of information
that a check constraint should hold is the mechanism it would use to check its values. This is
provided as an expression. Therefore, to create a constraint, you can click Expression and click
its ellipsis button. This would open the Check Constraint Expression dialog box.

To create the expression, first type the name of the column on which the constraint will apply,
followed by parentheses. In the parentheses, use the arithmetic and/or SQL operators we
studied already. Here is an example that will check that a new value specified for the Student
Number is greater than 1000:

After creating the expression, you can click OK. If the expression is invalid, you would receive
an error and given the opportunity to correct it.

You can create as many check constraints as you judge necessary for your table:
After creating the check constraints, you can click OK.

Programmatically Creating a Check Constraint


To create a check constraint in SQL, first create the column on which the constraint will apply.
Before the closing parenthesis of the table definition, use the following formula:

CONSTRAINT name CHECK (expression)

The CONSTRAINT and the CHECK keywords are required. As an object, make sure you
provide a name for it. Inside the parentheses that follow the CHECK operator, enter the
expression that will be applied. Here is an example that will make sure that the hourly salary
specified for an employee is greater than 12.50:

private void btnDatabase_Click(object sender, EventArgs e)


{
using (SqlConnection connection =
new SqlConnection("Data Source=(local);" +
"Database='Exercise1';" +
"Integrated Security=yes;"))
{
SqlCommand command =
new SqlCommand("CREATE TABLE Employees " +
"( " +
"[Employee Number] nchar(7), " +
"[Full Name] varchar(80), " +
"[Hourly Salary] smallmoney, " +
"CONSTRAINT CK_HourlySalary CHECK ([Hourly Salary] > 12.50) " +
");",
connection);

connection.Open();
command.ExecuteNonQuery();

MessageBox.Show("A new table named Employees has been created");


}
}

It is important to understand that a check constraint it neither an expression nor a function. A


check constraint contains an expression and may contain a function as part of its definition.

After creating the constraint(s) for a table, in the Object Explorer of the Microsoft SQL Server
Management Studio, inside the table's node, there is a node named Constraints and, if you
expand it, you would see the name of the constraint.

Using a Check Constraint


With the constraint(s) in place, during data entry, if the user (or your code) provides an invalid
value, an error would display. Here is an example:

Instead of an expression that uses only the regular operators, you can use a function to assist
in the checking process. You can create and use your own function or you can use one of the
built-in Transact-SQL functions.

Other Features of Data Entry


Is RowGuid
This property allows you to specify that a column with the Identity property set to Yes is used
as a ROWGUID column.

Data Import
Another technique used to get data into one or more tables consists of importing already
existing data from another database or from any other recognizable data file. Microsoft SQL
Server provides various techniques and means of importing data.

One of the easiest types of data that can be imported into SQL Server, and which is available
on almost all database environments, is the text file. Almost every database environment
allows you to import a text file but data from that file must be formatted appropriately. For
example, the information stored in the file must define the columns as distinguishable by a
character that serves as a separator. This separator can be the single-quote, the double-quote,
the comma, or any valid character. Data between the quotes is considered as belonging to a
distinct field. The last piece of information the file must provide is to distinguish each record
from another. This is easily taken car of by the end of line of a record. This is also recognized
as the carriage return.

These directives can help you manually create a text file that can be imported into Microsoft
SQL Server. In practicality, if you want to import data that resides on another database, you
can ask that application to create the source of data. Most applications can do that and format
the data.

To import data a data file (Students) to Microsoft SQL Server Management Studio:

1. In the Microsoft SQL Server Management Studio, you can right-click the database that
will own the table. If you do not have that database yet, you can first create it and give it
a name. After right-clicking the database, position the mouse on Tasks and click Import
Data...
2. On the first page of the wizard, you can click Next
3. On the second page, you should click the arrow of the Data Source combo box and select
Flat File Source
4. On the right side of File Name, you can enter the complete path to the database or click
the Browse button to locate and select the file. Here is an example:
5. Under Data Source, you should click Advanced to customize the names of the columns. To
do this, on the left side, click a column. On the right side, you can click Name and type a
name. Here is an example:

To see the list of columns, under Data Source, you can click Columns:
6. You can click Next 4 times and click Finish
7. At the end, you can click Close

After importing data, you should verify and possibly format it to customize its fields. To do this,
in the Object Explorer, you can expand the database in which you imported the list and expand
its Tables nodes. Right-click the new table and click Design. Click each field under Column
Name and change its properties appropriately. Here is an example:
After customizing the columns, make sure you save the table. You may receive a dialog box
filled with warnings:
After reading the text in the Validation Warnings dialog box, click Yes.

Database Visual Support: A Data Source


Introduction
So far, we have introduced and used to primary tools that Microsoft SQL
Server provides to create a database. We hardly did anything visually. To
make database development user friendly and graphically-driven,
Microsoft Visual Studio provides its own set of tools. Some of these tools are
available from the Toolbox. Some other tools are provided as classes you
can use as long as you are aware of them.

We defined a data set as a system

of values. The values are kept in one or more lists. We also saw that, to
support this system, the .NET Framework provides a class named DataSet.
This class is represented in the Data section of the Toolbox of Microsoft Visual
Studio by the object of the same name.

Practical Learning: Introducing Visual Database Support


1. Start Microsoft Visual C# and create a Windows Application named SolasPropertyRental5
2. In the Solution Explorer, right-click Form1.cs and click Rename
3. Type RentalProperties.cs and press Enter
4. Double-click the middle of the form and implement the Load event as follows:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace SolasPropertyRental5
{
public partial class RentalProperties : Form
{
public RentalProperties()
{
InitializeComponent();
}

private void RentalProperties_Load(object sender, EventArgs e)


{
using (SqlConnection cnnSolasPropertyRental =
new SqlConnection("Data Source=(local);" +
"Integrated Security='SSPI';"))
{
string strSolasPropertyRental =
"CREATE DATABASE SolasPropertyRental1;";

SqlCommand cmdSolasPropertyRental1 =
new SqlCommand(strSolasPropertyRental,
cnnSolasPropertyRental);

cnnSolasPropertyRental.Open();
cmdSolasPropertyRental1.ExecuteNonQuery();

MessageBox.Show("The SolasPropertyRental1 database has been


created");
}

using (SqlConnection cnnSolasPropertyRental =


new SqlConnection("Data Source=(local);" +
"Database='SolasPropertyRental1';" +
"Integrated Security='SSPI';"))
{
string strSolasPropertyRental =
"CREATE TABLE RentalProperties " +
"( " +
" RentalPropertyID int identity(1,1) NOT NULL, "
+
" PropertyCode char(7) NULL, " +
" PropertyType varchar(32) NULL, " +
" Bedrooms tinyint, " +
" Bathrooms float, " +
" MonthlyRent smallmoney, " +
" OccupancyStatus varchar(30) " +
");" +

"INSERT INTO dbo.RentalProperties(PropertyCode, PropertyType,"


+
" Bedrooms, Bathrooms, MonthlyRent, OccupancyStatus)" +
"VALUES('527-992', 'Apartment', 1, 1.00, 925.00, 'Available')"
+

"INSERT INTO dbo.RentalProperties(PropertyCode, PropertyType,"


+
" Bedrooms, Bathrooms, MonthlyRent, OccupancyStatus)" +
"VALUES('726-454', 'Apartment', 2, 1.00, 1150.50,
'Available')" +

"INSERT INTO dbo.RentalProperties(PropertyCode, PropertyType,"


+
" Bedrooms, Bathrooms, MonthlyRent, OccupancyStatus)" +
"VALUES('476-473', 'Single Family', 5, 3.50, 2250.85,
'Occupied')" +

"INSERT INTO dbo.RentalProperties(PropertyCode, PropertyType,"


+
" Bedrooms, Bathrooms, MonthlyRent, OccupancyStatus)" +
"VALUES('625-936', 'Townhouse', 3, 2.50, 1750.00,
'Available')" +

"INSERT INTO dbo.RentalProperties(PropertyCode, PropertyType,"


+
" Bedrooms, Bathrooms, MonthlyRent, OccupancyStatus)" +
"VALUES('179-768', 'Townhouse', 4, 2.50, 1920.00,
'Available')" +

"INSERT INTO dbo.RentalProperties(PropertyCode, PropertyType,"


+
" Bedrooms, Bathrooms, MonthlyRent, OccupancyStatus)" +
"VALUES('727-738', 'Single Family', 4, 2.00, 2140.50, 'Needs
Repair')" +

"INSERT INTO dbo.RentalProperties(PropertyCode, PropertyType,"


+
" Bedrooms, Bathrooms, MonthlyRent, OccupancyStatus)" +
"VALUES('371-801', 'Apartment', 3, 2.00, 1250.25,
'Available')" +

"INSERT INTO dbo.RentalProperties(PropertyCode, PropertyType,"


+
" Bedrooms, Bathrooms, MonthlyRent, OccupancyStatus)" +
"VALUES('241-536', 'Townhouse', 3, 1.50, 1650.50,
'Occupied')";
SqlCommand cmdSolasPropertyRental1 =
new SqlCommand(strSolasPropertyRental,
cnnSolasPropertyRental);

cnnSolasPropertyRental.Open();
cmdSolasPropertyRental1.ExecuteNonQuery();

MessageBox.Show("The RentalProperties table has been


created");
}
}
}
}
5. Execute the application
6. Close the form and return to your programming environment
7. Delete the whole code in the Load event

Adding a Data Source


Instead of using the DataSet object from the Toolbox, Microsoft Visual Studio provides a technique
automatically get a data set object by creating a connection to a database. The data set would be f
from the database. To use it, you can first display the Data Source window. To display the Data S
menu, you can click Data -> Show Data Sources.

To create a data source:

• On the main menu, you can click Data -> Add Data Source...
• In the Data Source window:

o You can click the Add New Data Source button


o You can right-click a blank area in the window and click Add New Data Source
o If the Add New Data Link appears (this is if the current application does not have a data
can click it

The first page of the Data Source Configuration allows you to specify the type of data source y
Database, Web Service, and Object
If you click Database and click Next, the second page of the wizard allows you to select an existing co
new one. To select an existing connection, you can click the arrow of the combo box and select from t
If you want to use, and select, an existing connection, you can click Next. If you click the New Con
would then have to select the server, the authentication, and the database.

In the third page of the wizard, you would specify a name for the connection string, and click Next.

In the fourth page of the wizard, you have the option of selecting one or more tables (and others) to
set. To do this, you can click the check boxes in the list. If you do not specify the tables, you can c
on, you can reconfigure the data source and select the tables (and/or others). After making your sel
Finish.

Practical Learning: Adding a Data Source


1. On the main menu, click Data -> Add New Data Source...
2. On the first page of the wizard, make sure Database is selected and click Next
3. In the second page of the wizard, click New Connection...
4. In the Server Name combo box, select the server or type (local)
5. In the Select or Enter a Database Name combo box, select SolasPropertyRental1
6. Click Test Connection
7. Click OK twice
8. On the Data Source Configuration Wizard, make sure the new connection is selected
Click the + button of Connection String
9. Click Next
10. Change the connection string to strSolasPropertyRental and click Next
11. Expand the Tables node and click the check box of RentalProperties
12. Change the name of the data set to dsSolasPropertyRental
13. Click Finish

The Characteristics of a Data Set


When you click the Finish button of the Data Source Configuration Wizard, Microsoft Visual Studio gen
(XML Schemas) and creates a data set object specially made and configured for your database. Pr
would create a class named after the name you gave to the data set and this class would be derive
class. To examine this created class, from the Solution Explorer, you can open the file that holds the n
followed by .Designer.cs.

Among the objects created in the data set class is a class that represents the table (or each table) you
page of the wizard. This class for the table is derived from the DataTable class an
System.Collections.IEnumerable interface. In order to use this new table in your code, you must d
it. Once you have done that, you can access the characteristics (properties, methods) of the table or i

Although the data set created from the Toolbox and the one generated from creating a data
differences, they still share the common definition of being data sets. As mentioned earlier, a da
adding a data source contains the table(s) (including its (their) column(s) and record(s), if any) you w
This allows you to access any of the characteristics we studied for a data set.

Database Visual Support: The Binding


Source
Introduction
Microsoft SQL Server does not provide user-friendly objects that a user can
use to perform the necessary operations of a regular application. That is
why you use Microsoft Visual Studio to create an application made of good
looking Windows controls. The controls of a Windows application are meant
to serve all types of applications, not just databases. If you want a
Windows control of your application to use the values of you database,
you must create a type of link between the control and the column of a
table. This process is referred to as binding. The object that serves this
connection is referred to as a binding source.

Creating a Binding Source


To support binding sources, the .NET Framework provides the BindingSource class from the Syste
namespace. Therefore, to programmatically create a binding source, you can declare a variable of ty
The class is equipped with three constructors. The default constructor allows you to simple declare t
an example:

private void btnBindingSource_Click(object sender, EventArgs e)


{
BindingSource bsNames = new BindingSource();
}

To visually create a binding source, from the Data section of the Toolbox, you can click BindingSourc
or container of your application. Because it is a non-visual object, its label would be positioned unde
then specify its characteristics in the Properties window.

The Data Source of a Binding Source


If you create a binding source, obviously you must give it a name. If you create it from the Toolbox
change its name in the Properties window. Besides, the second most important detail of a binding so
holds its values. This list is referred to as the data source. To make the binding source as flexible a
source can be almost any type of list, including an array. In reality, any class that implements the
candidate to be a data source.

To support data sources, the BindingSource class is equipped with a property named DataSourc
Object. The idea of using the vague Object type indicates that many types, but not all types, of ob
used as data sources.

To programmatically specify the data source of a binding source, first create your list, then assign it
property of your BindingSource object. Here is an example:

private void btnBindingSource_Click(object sender, EventArgs e)


{
BindingSource bsNames = new BindingSource();
List<string> strNames = new List<string>();

strNames.Add("Vicky Bisso");
strNames.Add("Amy Warren");
strNames.Add("Chrissie Childs");
strNames.Add("Martial Otto");

bsNames.DataSource = strNames;
}

To visually specify the data source of a binding source, access the Properties window of your BindingS
Properties window, click DataSource and click the arrow of its combo box:

• If you had not previously created a data source, you can click Add Project Data Source... This wo
Source Configuration Wizard that allows you to create and configure a data set
• If you had previously created a data set object, you can expand the Other Data Sources node an
Project Data Sources node. You would see the created data set and you can select it. Here is an e

Practical Learning: Creating a Binding Source


1. In the Data section of the Toolbox, click BindingSource and click the form
2. In the Properties window, change its name to bsSolasPropertyRental
3. Click DataSource and click the arrow its combo box
4. Expand the Other Data Sources node and the Project Data Sources node
5. Click dsSolasPropertyRental
Database Visual Support: The Table
Adapter
Introduction
After creating a data set and a data source, the database that holds the
values is ready to make them available to your application. The next step is
to indicate to each control where its data would come from. To assist you
with this task, Microsoft Visual Studio includes a tool that allows you to
create an object that can retrieve the values (data) from a table and make
them available to the Windows controls. This object is called a table adapter.

Creating a Table Adapter


There are various ways you can create a table adapter:

• If you had added a data source to your application and created a binding source, to create a tabl
the form, you can click the binding source object. In the Properties window, click the DisplayMe
its combo, select the name of the table:

After doing this, Microsoft Visual Studio would create a table adapter. You can then accept or cha
• Probably the best way to create a table adapter consists of generating it from the Data Source w
after creating a data source, from the Data Source window, you can drag the table node and drop
After dropping the table, Microsoft Visual Studio would create both a data set and a table adapter

Practical Learning: Creating a Table Adapter


1. While the binding source is still selected under the form, in the Properties window, click DataMem
arrow its combo box to select RentalProperties
2. Under the form, click rentalPropertiesTableAdapter and, in the Properties window, change its Nam
tadRentalProperties
3. Save the form

Database Visual Support: The Binding


Navigator
Introduction
If you drag a table from the Data Source window and drop it on a form,
Microsoft Visual Studio adds the necessary Windows controls to the form
and binds them to the columns of the table. To move from one record to
another, you would need a way to navigate among the records. You can
manually take care of this if you want. Alternatively, the .NET Framework
provides a class named BindingNavigator that contains all the necessary
functionality for this task.

Creating a Binding Navigator


There are various ways you can create a binding navigator:

• You can declare a variable of type BindingNavigator and configure it


• From the Data section of the Toolbox, you can drag a BindingNavigator object and drop it on a fo
then access the Properties window for the binding navigator. To support this, the BindingNavigato
property named BindingSource. You can access it from the Properties window of the binding navi
binding source
• If you drag a table from the Data Source window and drop it on a form, Microsoft Visual Studio w
configure a binding navigator for you

Practical Learning: Creating a Binding Navigator


1. In the Data section of the Toolbox, click BindingNavigator and click the form
2. In the Properties window, change its Name to bnRentalProperties
3. Still in the Properties window, click BindingSource and select bsSolasPropertyRental
4. In the Data section of the Toolbox, click DataGridView and click the form
5. Still in the Properties window, click DataSource and select bsSolasPropertyRental
6. Under the Properties window, click Edit Columns and configure the columns as follows:

Column HeaderText Width


RentalPropertyID Prop ID 50
PropertyCode Prop Code 70
PropertyType Property Type 90
Bedrooms Beds 50
Bathrooms Baths 50
MonthlyRent Monthly Rent 80
OccupancyStatus Status 90

7. In the Properties window, change the following characteristics:


(Name): dgvRentalProperties
ColumnHeadersHeightSizeMode: EnableResizing
8. Execute the application to see the result

9. Close the form and return to your programming environment

The Data Adapter


Introduction
In the previous sections, we reviewed some of the visual tools from the
Toolbox. Besides these, Microsoft Visual Studio provides other database
tools not available from the Toolbox.

You probably know already that the DataSet class was developed to help
you create and manage any type of list-based application. The high level of
flexibility that this class offers also allows it to directly integrate with a data-
based application, such as one created with Microsoft SQL Server. The
elements of a DataSet object directly relate to those of a database
application.

As mentioned already, a DataSet object is primarily used to create a list, not a formal database in
Microsoft SQL Server, Microsoft Access, or Corel Paradox, etc. This means that a list-based applicatio
is primarily a list. In order to read information of a formal database and use it in a DataSet list, yo
adapt it.

A data adapter is an object that takes data from a database, reads that data, and "fills" a DataSet o
In reverse, a data adapter can get the data stored in, or manipulated by, a DataSet object and fill o
with that data. To be able to apply these scenarios to any database, the .NET Framework provides va
each adapted for a particular category of database.

Creating a SQL Data Adapter


In order to read information from a Microsoft SQL Server database and make it available to a Data
use an object created from the SqlDataAdapter class. This class is defined in the System.Data.SqlC
the System.Data.dll library. The SqlDataAdapter class is derived from the DbDataAdapter class
the DataAdapter class. The DbDataAdapter and the DataAdapter classes are defined in the Syst
namespaces of the System.Data.dll library.

To use the SqlDataAdapter class, you can declare a variable of type SqlDataAdapter using one
such as the default constructor. Here is an example:

SqlDataAdapter dadVideoCollection = new SqlDataAdapter();

To allow the data adapter to use values produced from reading a table, the SqlDataAdapter class
property named SelectCommand of type SqlCommand. To specify how data would be read, yo
SqlCommand object that would carry a SQL statement:

SqlConnection cnnVideos = new SqlConnection(


"Data Source=(local);Database='VideoCollection';Integrated Security=yes");

string strVideos = "Blah Blah Blah";


SqlCommand cmdVideos = new SqlCommand(strVideos, cnnVideos);

Equipped with a SqlCommand object that holds a SQL statement, you can a
SqlDataAdapter.SelectCommand property of your data adapter. This would be done as follows:

private void Form1_Load(object sender, System.EventArgs e)


{
SqlConnection cnnVideos = new SqlConnection(
"Data Source=(local);Database='VideoCollection';Integrated Security=yes");
string strVideos = "Blah Blah Blah";
SqlCommand cmdVideos = new SqlCommand(strVideos, cnnVideos);

SqlDataAdapter dadVideoCollection = new SqlDataAdapter();


dadVideoCollection.SelectCommand = cmdVideos;

cnnVideos.Open();
cnnVideos.Close();
}

If you do not want to use the default constructor and the SelectCommand property separately, you
constructor of the SqlDataAdapter class. Its syntax is:

public SqlDataAdapter(SqlCommand selectCommand);

This constructor takes as argument a SqlCommand object. This time, instead of assigning th
SelectCommand property, you can pass that SqlCommand object to the SqlDataAdapter variabl
This would be done as follows:

private void Form1_Load(object sender, System.EventArgs e)


{
SqlConnection cnnVideos = new SqlConnection(
"Data Source=(local);Database='VideoCollection';Integrated Security=yes");

string strVideos = "Blah Blah Blah";


SqlCommand cmdVideos = new SqlCommand(strVideos, cnnVideos);

SqlDataAdapter dadVideoCollection = new SqlDataAdapter(cmdVideos);

cnnVideos.Open();
cnnVideos.Close();
}

Notice that with both constructors reviewed above, you must pass the connection to a SqlComm
alternative, you can create a connection but pass it directly to the data adapter when declaring its
you can use the third constructor of the SqlDataAdapter class. Its syntax is:

public SqlDataAdapter(string selectCommandText, SqlConnection selectConnection);

The first argument of this constructor expects a SQL statement, passed as string, that specifies how
read. The second argument is a SqlConnection object that specifies how the connection to the
handled. Here is an example:

private void Form1_Load(object sender, System.EventArgs e)


{
SqlConnection cnnVideos = new SqlConnection(
"Data Source=(local);Database='VideoCollection';Integrated Security=yes");

string strVideos = "Blah Blah Blah";

SqlDataAdapter dadVideoCollection = new SqlDataAdapter(strVideos, cnnVideos);

cnnVideos.Open();
cnnVideos.Close();
}

Instead of separately defining a SqlConnection and a SqlDataAdapter objects, you can directly p
string to the SqlDataAdapter object when declaring it. To do this, you can use the fourth
SqlDataAdapter class. Its syntax is:

public SqlDataAdapter(string selectCommandText, string selectConnectionString);

The first argument to this constructor is the statement that specifies how data would be read. The se
connection string. Here is an example of declaring a data adapter using this version of the SqlDataAd

private void Form1_Load(object sender, System.EventArgs e)


{
string strSelVideos = "Blah Blah Blah";
string strConVideos =
"Data Source=(local);Database='VideoCollection';Integrated Security=yes";

SqlDataAdapter dadVideoCollection = new SqlDataAdapter(strSelVideos, strConVideos);


}
Filling a Data Set
Before using a data set in your application, you would need a DataSet object. You can declare a Data
an example:

private void Form1_Load(object sender, System.EventArgs e)


{
SqlConnection cnnVideos = new SqlConnection(
"Data Source=(local);Database='VideoCollection';Integrated Security=yes");

string strVideos = "Blah Blah Blah";


SqlCommand cmdVideos = new SqlCommand(strVideos, cnnVideos);

SqlDataAdapter dadVideoCollection = new SqlDataAdapter(cmdVideos);

DataSet setVideos = new DataSet("VideoCollection");

cnnVideos.Open();
cnnVideos.Close();
}

If you declare your own DataSet variable, you would also eventually have to take care of some deta
as reading from XML, writing to XML, or serializing.

After reading data using a SqlDataAdapter object, you can used it to fill a DataSet object. To suppor
SqlDataAdapter class inherits the Fill() method from the DbDataAdapter class. This method is
versions. The first version of this method uses the following syntax:

public override int Fill(DataSet dataSet);

This version takes as argument an object of type DataSet. After this call, the dataset argument wou
records of the table read by the data adapter. When calling this method, you can pass it a DataSet
described above. Here is an example:

private void Form1_Load(object sender, System.EventArgs e)


{
SqlConnection cnnVideos = new SqlConnection(
"Data Source=(local);Database='VideoCollection';Integrated Security=yes");
string strVideos = "Blah Blah Blah";
SqlCommand cmdVideos = new SqlCommand(strVideos, cnnVideos);

SqlDataAdapter dadVideoCollection = new SqlDataAdapter(cmdVideos);


DataSet setVideos = new DataSet("VideoCollection");

dadVideoCollection.Fill(setVideos);

cnnVideos.Open();
cnnVideos.Close();
}

Once a DataSet contains records, you can use it as a data source for Windows controls. For exampl
populate a DataGrid control. Here is an example:

private void Form1_Load(object sender, System.EventArgs e)


{
SqlConnection cnnVideos = new SqlConnection(
"Data Source=(local);Database='VideoCollection';Integrated
Security=yes");

string strVideos = "Blah Blah Blah";


SqlCommand cmdVideos = new SqlCommand(strVideos, cnnVideos);

SqlDataAdapter dadVideoCollection = new


SqlDataAdapter(cmdVideos);

DataSet setVideos = new DataSet("VideoCollection");


dadVideoCollection.Fill(setVideos);

dataGridView1.DataSource = setVideos;

cnnVideos.Open();
cnnVideos.Close();
}

Once a DataSet has received data from a data adapter, it is made aware of the table(s), the column(s
that belong to the SQL statement of the data adapter. Based on this, you can bind the Window
application's form to the columns of a DataSet.

The Tables of a DataSet


The tables of a DataSet object are stored in the DataSet.Tables property that is of type DataTab
filling up a DataSet, if the selection statement of the data adapter includes only one table (in future
that a SQL statement can include more than one table), as done in the above data adapter, th
statement can be identified with the index of 0 as in DataTableCollection[0]. If the statement incl
only a 0 index can be used. As the DataTableCollection[0] value allows you to identify a table, y
table-related information with this information. For example, you can get the object name of the ta
the DataMember property of a DataGrid control. Here is an example:

private void Form1_Load(object sender, System.EventArgs e)


{
SqlConnection cnnVideos = new SqlConnection(
"Data Source=(local);Database='VideoCollection';Integrated
Security=yes");
string strVideos = "Blah Blah Blah";
SqlCommand cmdVideos = new SqlCommand(strVideos, cnnVideos);

cnnVideos.Open();
SqlDataAdapter dadVideoCollection = new SqlDataAdapter(cmdVideos);

DataSet setVideos = new DataSet("VideoCollection");


dadVideoCollection.Fill(setVideos);

dataGrid1.DataSource = setVideos;
dataGrid1.DataMember = setVideos.Tables[0].TableName;

cnnVideos.Close();
}

Remember that the DataSet.Tables[Index] value gives you access to a table as an object and
necessary.

The Columns of a Table of a DataSet


Just as you can use the filled DataSet to locate a table by its index, inside of the identified table, y
particular column you need. As reviewed in previous lessons, the columns of a table are stored in the
of a DataTable object and the Columns property is of type DataColumnCollection. Each column in
be identified by its index. The first column has an index of 0. The second has an index of 1, and so
identified a column, you can manipulate it as you see fit. In the following example, since we (behave
the name of the second column, a message box displays that information for us:

private void Form1_Load(object sender, System.EventArgs e)


{
SqlConnection cnnVideos = new SqlConnection(
"Data Source=(local);Database='VideoCollection';Integrated
Security=yes");

string strVideos = "Blah Blah Blah";


SqlCommand cmdVideos = new SqlCommand(strVideos, cnnVideos);

cnnVideos.Open();
SqlDataAdapter dadVideoCollection = new
SqlDataAdapter(cmdVideos);

DataSet setVideos = new DataSet("VideoCollection");


dadVideoCollection.Fill(setVideos);
dataGrid1.DataSource = setVideos;
dataGrid1.DataMember = setVideos.Tables[0].TableName;

DataColumn colSecond = setVideos.Tables[0].Columns[1];


MessageBox.Show("The name of the second column is " +
colSecond.ColumnName);

cnnVideos.Close();
}

Updating a Record Using the Data Adapter


When visiting the records of a table using a form of your application, if you provide the means for the
one record to another, if the user gets to a record and changes something in it, that record would n
updated when the user moves to another record. To update a record using the data adapter, the Sq
inherits the Update() method from its parent the DbDataAdapter. The Update() method is overloa
One of its versions uses the following syntax:

public override int Update(DataSet dataSet);

This version takes a DataSet object as argument. This means that the data adapter would read the i
the DataSet and update the database with it. This is probably one of the easiest or fastest means o
table.

The Records of a Table of a Dataset


After filling out a DataSet with information from a data adapter, the records of the table(s) includ
statement become available from the DataSet object. As reviewed in Lesson 14, the records of a tab
Rows property of the table. We have already seen how to locate a table and how to identify a column
you can use the techniques reviewed in Lesson 14.

Data entry with a data adapter is performed just a few steps once you have properly bound the con
a DataSet object. To start, you can access the form's BindingContext property to get its Bin
property. The second version of this property allows you to specify the data source and the table na
the DataSet object that holds the records and the table that holds the data, you can first call the
method to suspend any record editing that was going on. After this, call the AddNew() method to ge
a new record. This allows the user to enter values in the Windows control.

Introduction to the Records of a Database


Introduction
A table is an object that holds the information of a database. This means
that the database must first exist. Here is an example of creating such a
database:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Exercise
{
public partial class Exercise : Form
{
public Exercise()
{
InitializeComponent();
}

private void btnDatabase_Click(object sender, EventArgs e)


{
using (SqlConnection connection =
new SqlConnection("Data Source=(local);" +
"Integrated Security=yes;"))
{
SqlCommand command =
new SqlCommand("CREATE DATABASE VideoCollection1;",
connection);
connection.Open();
command.ExecuteNonQuery();

MessageBox.Show("A database named VideoCollection1 has been created.");


}
}
}
}

Here is a sample table:

private void btnDatabase_Click(object sender, EventArgs e)


{
using (SqlConnection connection =
new SqlConnection("Data Source=(local);" +
"Database='VideoCollection1';" +
"Integrated Security=yes;"))
{
SqlCommand command =
new SqlCommand("CREATE TABLE Videos (" +
"[Video Title] varchar(120), " +
"Director varchar(100), " +
"[© Year] smallint, " +
"Length varchar(30), " +
"Rating varchar(6));",
connection);
connection.Open();
command.ExecuteNonQuery();

MessageBox.Show("A table named \"Videos\" has been created.");


}
}

Because a table is the central part of a database, the information it holds must be meticulously o
manage its information, data of a table is arranged in a series of fields called cells. Once a table conta
can review it using either the Microsoft SQL Server Management Studio or a Windows application.

Practical Learning: Introducing Database Records


1. Start Microsoft Visual C# and create a new Windows Application named CollegeParkAutoRepa
2. In the Server Explorer, right-click Data Connections and click Add New SQL Server Database
3. In the Server Name combo box, select the server or type (local)
4. Set the name of the database to CPAR2 and click OK
5. In the Server Explorer, expand server.CPAR2.dbo
6. Under it, right-click Tables and click Add New Table
7. Complete the table with following columns:

Column Name Data Type


ReceiptNumber int
OrderDate datetime
OrderTime datetime
CustomerName varchar(80)
CarMake varchar(50)
CarModel varchar(50)
CarYear smallint
ProblemDescription text
TotalParts money
TotalLabor money
TaxRate decimal(6,2)
TaxAmount money
TotalOrder money
Recommendations text

8. To save the table, on the Standard toolbar, click the Save button
9. Type RepairOrders as the name of the table and click OK
10. Close the RepairOrders window
11. In the Solution Explorer, right-click Form1.cs and click Rename
12. Type OrderProcessing.cs and press Enter twice
13. Design the form as follows:
14. Design the form as follows:
Control Name Text Other Properties
Group Order Identification
Label Order Date/Time:
DateTimePicker dtpOrderDate
Format: Time
DateTimePicker dtpOrderTime
ShowUpDown: True
Label Customer Name:
TextBox txtCustomerName
Label Make / Model:
TextBox txtMake
TextBox txtModel
Label Year:
TextBox txtCarYear TextAlign: Right
Label Problem Description:
Multiline: True
TextBox txtProblemDescription
ScrollBars: Vertical
GroupBox Order Summary
Label Total Parts:
TextBox txtTotalParts 0.00 TextAlign: Right
Label Total Labor:
TextBox txtTotalLabor 0.00 TextAlign: Right
Label Tax Rate:
TextBox txtTaxRate 7.75 TextAlign: Right
Label %
Label Tax Amount:
TextBox txtTaxAmount 0.00 TextAlign: Right
Label Total Order:
TextBox txtTotalOrder 0.00 TextAlign: Right
Label Recommendations
Multiline: True
TextBox txtRecommendations
ScrollBars: Vertical
Button btnSaveRepairOrder Save Repair Order
Button btnNewRepairOrder New Repair Order/Reset
Button btnClose Close

15. Double-click the New Repair Order button and implement its event as follows:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace CollegeParkAutoRepair3
{
public partial class OrderProcessing : Form
{
public OrderProcessing()
{
InitializeComponent();
}

private void btnNewRepairOrder_Click(object sender, EventArgs


e)
{
dtpOrderDate.Value = DateTime.Today.Date;
dtpOrderTime.Value = DateTime.Now;
txtCustomerName.Text = ""; txtCarMake.Text = "";
txtCarModel.Text = ""; txtCarYear.Text = "";
txtProblemDescription.Text = "";

txtTotalParts.Text = "0.00"; txtTotalLabor.Text = "0.00";


txtTaxRate.Text = "7.75"; txtTaxAmount.Text = "0.00";
txtTotalOrder.Text = "0.00"; txtRecommendations.Text =
"0.00";
}
}
}
16. Return to the form

Table Data Navigation


Data Navigation consists of displaying and viewing data. Because information of a database is sto
primary means of viewing data consists of opening a table in a view that displays its information.

When a table displays its records, you navigate through its fields using the mouse or the keyboard.
get to any cell, you can just click it. To navigate through records using the keyboard, you can press:

• The right arrow key to move to the right cell; if the caret is already in the most right cell, it would
first cell of the next record, up to the last empty cell of the first empty record
• The left arrow key to move to the previous cell; if the caret is in, or reaches, the most left cell of
nothing would happen when you press the the left arrow key
• The down arrow key to move to the cell under the current one; if the caret is already in the last c
column, nothing would happen
• The up arrow key to move to the cell just above the current one; if the caret is already in the firs
column, nothing would happen
• The Page Down to move to the next group of cell that would correspond to the next page; if the
less than a complete page, the caret would move to the last cell of the current column
• The Page Up to move to the next group of cell that would correspond to the next page; if the num
less than a complete page, the caret would move to the first cell of the current column

Visual Data Entry


Introduction
As you are probably aware already, columns are used to organize data by
categories. Each column has a series of fields under the column header. One
of the actual purposes of a table is to display data that is available for each
field under a particular column. Data entry consists of providing the
necessary values of the fields of a table. Data is entered into a field and
every time this is done, the database creates a row of data. This row is
called a record. This means that entering data also self-creates rows.

There are various ways you can perform data entry for a Microsoft SQL
Server table:

• In Microsoft SQL Server Management Studio, you can use a table from the Object Explorer
• In Microsoft SQL Server Management Studio, you can enter data by typing code in a query windo
• In Microsoft Visual Studio, you can open the table from the Server Explorer
• You can import data from another object or another database
• You can use an external application such as Microsoft Access, Microsoft Visual Basic, Borland C+
Microsoft Visual C++, Borland Delphi, Microsoft Visual Basic, C#, Visual C#, J#, etc
• You can create a Windows application in Microsoft Visual Studio

Using the Server Explorer


Probably the easiest and fastest way to enter data into a table is by using either Microsoft SQL Server
or Microsoft Visual Studio. Of course, you must first open the desired table from a database conne
Explorer, after expanding the connection to the database and the Tables nodes, right-click the des
Show Table Data. If the table does not contain data, it would appear with one empty row. If some re
already, their rows would show and the table would provide an empty row at the end, expecting a new

To perform data entry on a table, you can click in a cell. Each column has a title, called a caption
section on top is called a column header. In Microsoft SQL Server, it displays the actual name of the c
the column header to know what kind of data should/must go in a field under a particular column. Th
design your columns meticulously. After identifying a column, you can type a value. Except for text-ba
can reject a value if the value does not conform to the data type that was set for the column. This
circumstances, you may have to provide some or more explicit information to the user.

Practical Learning: Introducing Data Entry


1. In the Server Explorer, if necessary, expand the Tables node under Server.CPAR2.dbo.
Right-click the RepairOrders node and click Show Table Data
2. Click the empty box under CustomerName, type Jamil Harrah
3. Click the box under ReceiptNumber, type 1244LPD and press Enter
4. Notice that you receive an error because the letters are not allowed:

5. Click OK on the error message box.


6. Change the value to 1244 and press Tab
7. Under OrderDate, type 2006/02/16 and press the down arrow key
8. Notice that the date changes to 2/16/2006
9. For the second box under OrderDate, type 06/06/06 and press Tab
10. For the OrderTime of the second record, type 14:48 and press the up arrow key
11. Notice that the value changes to today's date followed by the time you had entered
12. For the first record under OrderTime, type 04:25 PM and press Enter
13. Close the RepairOrders window

Data Entry With SQL


Introduction
To perform data entry using SQL:

• In the Object Explorer of Microsoft SQL Server Management Studio,


you can right-click the table, position the mouse on Script Table As ->
INSERT To -> New Query Editor Window
• Open an empty query window and type your code

In the SQL, data entry is performed using the INSERT combined with the
VALUES keywords. The primary statement uses the following syntax:

INSERT TableName VALUES(Column1, Column2, Column_n);

Alternatively, or to be more precise, you can use the INTO keyword between the INSERT keyword
factor to specify that you are entering data in the table. This is done with the following syntax:

INSERT INTO TableName VALUES(Column1, Column2, Column_n)

The TableName factor must be a valid name of an existing table in the database you are using. If the
SQL interpreter would simply consider that the table you are referring to doesn't exist. Consequently
an error.

The VALUES keyword indicates that you are ready to list the values of the columns. The values of t
included in parentheses.

If the column is a BIT data type, you must specify one of its values as 0 or 1.

If the column is a numeric type, you should pay attention to the number you type. If the column
receive an integer (int, bigint, smallint), you should provide a valid natural number without the deci

If the column is for a decimal number (float, real, decimal, numeric), you can type the valu
separator (the period for US English).

If the column was created for a date or time data type (datetime or smalldatetime), make sure
date.

If the data type of a column is a string type, you should include its entry between single quotes. F
number can be specified as 'HHR-604' and a middle initial can be given as 'D'.

In your Windows application, you can pass the INSERT statement to a command object.

Adjacent Data Entry


The most common technique of performing data entry requires that you know the sequence of fields
you want to enter data. With this subsequent list in mind, enter the value of each field in its correct
example:

private void btnDatabase_Click(object sender, EventArgs e)


{
using (SqlConnection connection =
new SqlConnection("Data Source=(local);" +
"Database='VideoCollection1';" +
"Integrated Security=yes;"))
{
SqlCommand command =
new SqlCommand("INSERT INTO Videos " +
"VALUES('A Few Good Men','Rob Reiner',1992,'138 Minutes', 'R');",
connection);
connection.Open();
command.ExecuteNonQuery();

MessageBox.Show("A new record has been created.");


}
}

During data entry on adjacent fields, if you do not have a value for a numeric field, you should type
string field whose data you do not have and cannot provide, type two single-quotes '' to specify an em

Practical Learning: Performing Data Entry


1. On the OrderProcessing form, double-click the Save Repair Order button and implement its event

private void btnSaveRepairOrder_Click(object sender, EventArgs e)


{
string strConnection =
"Data Source=(local);" +
"Database='CollegeParkAutoRepair1';" +
"Integrated Security=yes;";
string strRepairOrder = "INSERT INTO RepairOrders(CustomerName, "
+
"CarMake, CarModel, CarYear, ProblemDescription, " +
"TotalParts, TotalLabor, TotalOrder) " +
"VALUES ('" + txtCustomerName.Text + "', '" +
txtCarMake.Text + "', '" + txtCarModel.Text + "', '" +
txtCarYear.Text + "', '" + txtProblemDescription.Text
+
"', '" + txtTotalParts.Text + "', '" +
txtTotalLabor.Text +
"', '" + txtTotalOrder.Text + "');";

using (SqlConnection connection = new


SqlConnection(strConnection))
{
SqlCommand command =
new SqlCommand(strRepairOrder, connection);

connection.Open();
command.ExecuteNonQuery();

MessageBox.Show("A new repair order has been created.");


}
}
2. Execute the application
3. Enter all values in the form
4. Click the Save Repair Order button. Here is an example:

5. Close the form and return to your programming environment

Random Data Entry


The adjacent data entry we have performed requires that you know the position of each column. T
alternative that allows you to perform data entry using the name of a column instead of its position
provide the values of columns in an order of your choice. We have just seen a few examples where th
the fields were not available during data entry. Instead of remembering to type 0 or NULL for such fie
quotes for a field, you can use the fields' names to specify the fields whose data you want to provide.

To perform data entry in an order of your choice, you must provide your list of the fields of the table
all columns or provide a list of the same columns but in your own order. In the same way, you don't h
for all fields, just those you want, in the order you want.

Here are examples:

private void btnDatabase_Click(object sender, EventArgs e)


{
using (SqlConnection connection =
new SqlConnection("Data Source=(local);" +
"Database='VideoCollection1';" +
"Integrated Security=yes;"))
{
SqlCommand command =
new SqlCommand(
"INSERT INTO Videos([Video Title], Director, [© Year], Length) " +
"VALUES('The Silence of the Lambs','Jonathan Demme',1991,'118 Minutes'); " +
"INSERT INTO Videos([Video Title], Director, Length) " +
"VALUES('The Distinguished Gentleman', 'James Groeling', '112 Minutes'); " +
"INSERT INTO Videos([Video Title], Director, Length) " +
"VALUES('The Lady Killers', 'Joel Coen & Ethan Coen', '104 Minutes'); " +
"INSERT INTO Videos([Video Title], Director, Length) " +
"VALUES('Ghosts of Mississippi', 'Rob Reiner', '130 Minutes');",
connection);
connection.Open();
command.ExecuteNonQuery();

MessageBox.Show("A few records have been created.");


}
}
Practical Learning: Performing Data Entry
1. Change the code of the Save Repair Order button as follows:

private void btnSaveRepairOrder_Click(object sender, EventArgs e)


{
string strConnection =
"Data Source=(local);" +
"Database='CPAR2';" +
"Integrated Security=yes;";
string strRepairOrder = "INSERT INTO RepairOrders(CustomerName, "
+
"CarMake, CarModel, CarYear, ProblemDescription, " +
"TotalParts, TotalLabor, TotalOrder) " +
"VALUES ('" + txtCustomerName.Text + "', '" +
txtCarMake.Text + "', '" + txtCarModel.Text + "', '" +
txtCarYear.Text + "', '" + txtProblemDescription.Text
+
"', '" + txtTotalParts.Text + "', '" +
txtTotalLabor.Text +
"', '" + txtTotalOrder.Text + "');";
using (SqlConnection connection = new
SqlConnection(strConnection))
{
SqlCommand command =
new SqlCommand(strRepairOrder, connection);

connection.Open();
command.ExecuteNonQuery();

MessageBox.Show("A new repair order has been created.");


}
}
2. Execute the application
3. Enter the customer name, the name of the car, its model, its year, a description of a job to be pe
the parts, the cost of the labor, and the total price paid to repair
4. Click the Save Repair Order button
5. Enter the values again and click the Save Repair Order button again
6. Close the form and return to your programming environment

Record Maintenance: Deleting Records


Deleting a Record
Record maintenance includes viewing records, looking for one or more
records, modifying one or more records, or deleting one or more records.

If you find out that a record is not necessary, not anymore, or is misplaced,
you can remove it from a table.

To visually delete a record in SQL in Microsoft SQL Server Management


Studio or Microsoft Visual Studio, open the table to show its records. On the
table, you can right-click the gray box on the left of a record and click
Delete:
You can also first select the record and press Delete. You would receive a warning to confirm your inte

In SQL, to delete a record, use the DELETE FROM statement associated with the WHERE operator. T
is:

DELETE FROM TableName


WHERE Condition(s)

The TableName factor is used to identify a table whose record(s) would be removed.

The Condition(s) factor allows you to identify a record or a group of records that carries a criterion
precise in your criteria so you would not delete the wrong record(s).

Here is an example used to remove a particular record from the table:

private void btnDatabase_Click(object sender, EventArgs e)


{
using (SqlConnection connection =
new SqlConnection("Data Source=(local);" +
"Database='Exercise1';" +
"Integrated Security=yes;"))
{
SqlCommand command =
new SqlCommand("DELETE FROM Videos " +
"WHERE VideoTitle = 'The Lady Killers';",
connection);
connection.Open();
command.ExecuteNonQuery();
}
}
Deleting Many Records
Instead of one, you can delete more than one record at a time. To do this, first select the group of
range or at random, then either right-click the selection and click Delete or press Delete:
After clicking Delete, you would receive a warning. If you still want to delete the records, you can click

To programmatically delete a group or records, apply the DELETE FROM table formula and use a W
can identify each one of the records.

Deleting all Records


If you think all records of a particular table are, or have become, useless, you can clear the whole tab
keep its structure.

To visually delete all records from a table, open it in design view, first select all of them, and pres
receive a warning. If you still want to delete the records, click Yes. If you change your mind, click No

Using SQL, to clear a table of all records, use the DELETE operator with the following formula:

DELETE TableName;

When this statement is executed, all records from the TableName factor would be removed from t
when doing this because once the records have been deleted, you cannot get them back.

Practical Learning: Deleting Records


1. On the form double-click the Close button and implement it as follows:

private void btnClose_Click(object sender, EventArgs e)


{
string strConnection =
"Data Source=(local);" +
"Database='CPAR2';" +
"Integrated Security=yes;";
string strRepairOrder = "DELETE RepairOrders;";

using (SqlConnection connection = new


SqlConnection(strConnection))
{
SqlCommand command = new SqlCommand(strRepairOrder,
connection);

connection.Open();
command.ExecuteNonQuery();

MessageBox.Show("All repair orders have been deleted.");


}

Close();
}

2. Execute the application to display the form


3. Click the Close button

4. Return to your programming environment and change the code of the Close button as follows

private void btnClose_Click(object sender, EventArgs e)


{
Close();
}
Record Maintenance: Updating the
Records
Updating a Record
Updating a record consists of changing its value for a particular column. To
visually update a record, open the table to show its records, locate the
value that needs to be updated and edit it.

To update a record using SQL:

• In the Object Explorer of Microsoft SQL Server Management Studio,


you can right the table, position the mouse on Script Table As ->
UPDATE To -> New Query Editor Window
• Open an empty query window and type your code

To support record maintenance operations, the SQL provides the UPDATE keyword that is used to
which you want to maintain the record(s). The basic formula to use is:

UPDATE TableName
SET ColumnName = Expression

With this formula, you must specify the name of the involved table as the TableName factor of ou
statement allows you to specify a new value, Expression, for the field under the ColumnName column.

Updating all Records


Imagine that, at one time, on a particular table, all records need to receive a new value under one
certain columns. There is no particular way to visually update all records of a table. You can just open
records, and then change them one at a time.

In SQL, the primary formula of the UPDATE statement as introduced on our formula can be used to
Here is an example:

private void btnDatabase_Click(object sender, EventArgs e)


{
using (SqlConnection connection =
new SqlConnection("Data Source=(local);" +
"Database='VideoCollection1';" +
"Integrated Security=yes;"))
{
SqlCommand command =
new SqlCommand("UPDATE Videos SET Rating = 'R';",
connection);
connection.Open();
command.ExecuteNonQuery();

MessageBox.Show("All video records have been rated R.");


}
}

With this code, all records of the Videos table will have their Rating fields set to a value of R:

Editing a Record
Editing a record consists of changing a value in a field. It could be that the field is empty, such as th
'The Lady Killers' video of the following table. It could be that the value is wrong, such as the Dire
Distinguished Gentleman' video of this table:

Video Title Director © Year Length Rating


A Few Good Men Rob Reiner 1992 138 Minutes R
The Silence of the Lambs Jonathan Demme 1991 118 Minutes
The Distinguished Gentleman James Groeling 112 Minutes R
The Lady Killers Joel Coen & Ethan Coen 104 Minutes R
Ghosts of Mississippi Rob Reiner 130 Minutes

To edit a record, first open the table to view its records. Locate the record, the column on which yo
locate the value you want to change, then change it.

In SQL, you must provide a way for the interpreter to locate the record. To do this, you would as
operator in an UPDATE statement using the following formula:

UPDATE TableName
SET ColumnName = Expression
WHERE Condition(s)

The WHERE operator allows you to specify how the particular record involved would be identified. It i
most cases, that the criterion used be able to uniquely identify the record. In the above table, imag
interpreter to change the released year to 1996 where the director of the video is Rob Reiner. The
would be written as follows:

UPDATE Videos
SET YearReleased = 1996
WHERE Director = 'Rob Reiner';

In the above table, there are at least two videos directed by Rob Reiner. When this statement is
records whose director is Rob Reiner would be changed, which would compromise existing records th
change. Therefore, make sure your WHERE statement would isolate one particular record or only th
updated. Here is an example used to change the name of the director of a particular video:

private void btnDatabase_Click(object sender, EventArgs e)


{
using (SqlConnection connection =
new SqlConnection("Data Source=(local);" +
"Database='VideoCollection1';" +
"Integrated Security=yes;"))
{
SqlCommand command =
new SqlCommand("UPDATE Videos " +
"SET Director = 'Jonathan Lynn' " +
"WHERE [Video Title] = 'The Distinguished Gentleman';",
connection);
connection.Open();
command.ExecuteNonQuery();

MessageBox.Show("The director of 'The Distinguished Gentleman' " +


"video has been updated.");
}
}

Relational Databases
A relational database is a system in which information flows from one
database object to another. For example, if you create an application used
to process orders for a car rental business, you can create one table for the
cars and a separate table used to process customers orders. When
processing an order, you would want to simply select a car in the order
processing table. That way, you would avoid entering new information about
a particular car every time it is rented. If you do this, you may have one
order that has a car named Toyota Corola with the tag number FFG802 and
another order with the car Toyoda Corolla with the tag number FFF802 when
in fact both orders refer to the same car. Therefore, you should avoid any
chance to type the information for the car when processing an order.

To apply the rules of relational databases, you create some types of relationships among the objects o

The transactions among the various objects of a database should make sure information of one ob
another object. The objects that hold information, as we have mentioned already, are the tables.

To manage the flow of information from one table (A) to another table (B), the table that holds the i
make it available to other tables, such as B. There are various issues that must be dealt with:

1. You must be able to uniquely identify each record from a table (A) without any confusion. For exa
a list of cars on a table, you should make sure that there is a unique (no duplicate) tag number f
each car should have one and must have one tag number. This ensures that there are no duplica
table.
2. A table (A) that holds information should make that information available to other tables (such as
3. Two tables must not serve the same purpose. Once you have unique information on each table, o
its data available to other tables that need it so that the same information should not be entered
table

These problems are solved by specifying a particular column as the "key" of the table. Such a column
primary key.

In a relational database, which is the case for most of the databases you will be creating, each table
one primary key. As an example, a primary key on an car table of a car rental company can be set on
because each car should have a unique tag number. A table can also use more than one column to re
key if you judge it necessary.

Once you have decided that a table will have a primary key, you must decide what type of data that
are building a table that can use a known and obvious field as unique, an example would be the shelf
you can set its data type as char or varchar and make it a primary key. In many other cases, for ex
decide on a particular field that would hold unique information, an example would be customers
should create your own unique field and make it the Primary Key. Such a field should have an int data

Visually Creating a Primary Key


To create a primary key in the Microsoft SQL Server Management Studio or Microsoft Visual Studio
a column and specify its data type:

• Then, on the toolbar, click the Set Primary Key button


• You can also right-click a column and click Set Primary Key

Here is an example:

Creating a Primary Key With SQL


To create a primary column using SQL, the primary thing to do is, on the right side of the colu
PRIMARY KEY. Here is an example:

CREATE TABLE Persons


(
PersonID int identity(1,1) PRIMARY KEY NOT NULL,
FirstName varchar(20),
LastName varchar(20) NOT NULL
);
The Primary Key Constraint
In the SQL, you can give a specific name to a primary key. To do this, you can first create the colum
before the closing parenthesis of the table, specify the primary key column using the following formula

CONSTRAINT PrimaryKeyName PRIMARY KEY(ColumnName)

In this formula, the CONSTRAINT keyword and the PRIMARY KEY (case-insensitive) expression
PrimaryKeyName placeholder, enter the name you want to give to the primary key. In the parenthes
KEY expression, enter the name of the column that will be used as the primary key. Here is an examp

CREATE TABLE Persons


(
PersonID int identity(1,1) NOT NULL,
FirstName varchar(20),
LastName varchar(20) NOT NULL,
CONSTRAINT PrimKeyPeople PRIMARY KEY(PersonID)
);

By convention or tradition, the name of the primary starts with PK_ followed by the name of th
example:

USE Exercise2;
GO

CREATE TABLE Persons


(
PersonID int identity(1,1) NOT NULL,
FirstName varchar(20),
LastName varchar(20) NOT NULL,
CONSTRAINT PK_Persons PRIMARY KEY(PersonID)
);
GO

Establishing a Relationship
Introduction
As mentioned already, a relational database is one in which information
flows from one table to another. To prepare the tables for this, you create
primary and foreign keys, which we have done so far. Once the tables are
ready, you can link them, which is referred to as creating a relationship
between two tables. If you did not create a foreign key with SQL code, you
can create it when establishing a relationship between two tables.

Creating a Relationship
To create a relationship between two tables

1. Open the child table in the design view


2. Right-click (anywhere in) the table and click Relationships...
If the (necessary) foreign key does not exist, click Add and specify its name under Identity) on th
side
3. Under Selected Relationships, click the foreign key that will hold the relationship
4. On the right side, expand Tables And Columns Specification

5. Click its ellipsis button


6. In the Primary Key Table combo box, select the parent table that holds the primary data
7. Under the parent table, click and select its primary key column
8. Under Foreign Key Table, make sure the name of the current table is set.
Under the name of the child table, click and select the name of the foreign key column. Here is a
example:

9. Click OK.
When a relationship has been created, it would show in the Tables And Column Specification sect
10. In the same way, you can create other relationships by clicking Add and configuring the link.
Once you have finished, click Close

Practical Learning: Creating Relationships


1. Start Microsoft Visual C# and create a new Windows Application named Exercise31
2. In the Solution Explorer, right-click Form1.cs and click Rename
3. Type Exercise.cs and press Enter twice
4. Double-click the middle of the form
5. To create a database, including the tables with their primary keys and their foreign keys, implem
Load event as follows:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace Exercise31
{
public partial class Exercise : Form
{
public Exercise()
{
InitializeComponent();
}

private void Exercise_Load(object sender, EventArgs e)


{
using (SqlConnection conYNB =
new SqlConnection("Data Source=(local); " +
"Integrated Security='SSPI';"))
{
string strCreateDatabase = "IF EXISTS ( " +
"SELECT name " +
"FROM sys.databases " +
"WHERE name = N'BethesdaCarRental1' " +
") " +
"DROP DATABASE BethesdaCarRental1; " +
"CREATE DATABASE BethesdaCarRental1";

SqlCommand cmdYNB = new SqlCommand(strCreateDatabase,


conYNB);

conYNB.Open();
cmdYNB.ExecuteNonQuery();

MessageBox.Show("A database named N'BethesdaCarRental1 has been


created");
}

using (SqlConnection conYNB =


new SqlConnection("Data Source=(local); " +
"Database='BethesdaCarRental1'; " +
"Integrated Security='SSPI';"))
{
string strCreateTable = "CREATE TABLE RentalRates( " +
"RentalRateID int identity(1, 1) NOT NULL, " +
"Daily smallmoney, Weekly smallmoney, " +
"Monthly smallmoney, Weekend smallmoney, " +
"CONSTRAINT PK_RentalRates PRIMARY KEY
(RentalRateID));";

SqlCommand cmdYNB = new SqlCommand(strCreateTable,


conYNB);

conYNB.Open();
cmdYNB.ExecuteNonQuery();
MessageBox.Show("A table named RentalRates has been
created");
}

using (SqlConnection conYNB =


new SqlConnection("Data Source=(local); " +
"Database='BethesdaCarRental1'; " +
"Integrated Security='SSPI';"))
{
string strCreateTable = "CREATE TABLE Employees( " +
"EmployeeID int identity(1, 1) NOT NULL, " +
"EmployeeNumber nchar(5), " +
"FirstName varchar(32), " +
"LastName varchar(32) NOT NULL, " +
"FullName AS (([LastName]+', ')+[FirstName]),
" +
"Title varchar(80), " +
"HourlySalary smallmoney, " +
"CONSTRAINT PK_Employees PRIMARY KEY
(EmployeeID));";

SqlCommand cmdYNB = new SqlCommand(strCreateTable,


conYNB);

conYNB.Open();
cmdYNB.ExecuteNonQuery();
MessageBox.Show("A table named Employees has been
created");
}

using (SqlConnection conYNB =


new SqlConnection("Data Source=(local); " +
"Database='BethesdaCarRental1'; " +
"Integrated Security='SSPI';"))
{
string strCreateTable = "CREATE TABLE Customers( " +
"CustomerID int identity(1, 1) NOT NULL, " +
"DrvLicNumber varchar(50), " +
"FullName varchar(80), " +
"Address varchar(100) NOT NULL, " +
"City varchar(50), " +
"State varchar(50), " +
"ZIPCode varchar(20), " +
"CONSTRAINT PK_Customer PRIMARY KEY
(CustomerID));";

SqlCommand cmdYNB = new SqlCommand(strCreateTable,


conYNB);

conYNB.Open();
cmdYNB.ExecuteNonQuery();
MessageBox.Show("A table named Customers has been
created");
}

using (SqlConnection conYNB =


new SqlConnection("Data Source=(local); " +
"Database='BethesdaCarRental1'; " +
"Integrated Security='SSPI';"))
{
string strCreateTable = "CREATE TABLE Cars( " +
"CarID int identity(1, 1) NOT NULL, " +
"TagNumber varchar(20), " +
"Make varchar(50), " +
"Model varchar(50) NOT NULL, " +
"CarYear smallint, " +
"Category varchar(50), " +
"PictureLocation varchar(200), " +
"CDPlayer bit, " +
"DVDPlayer bit, " +
"Available bit, " +
"CONSTRAINT PK_Car PRIMARY KEY (CarID));";

SqlCommand cmdYNB = new SqlCommand(strCreateTable,


conYNB);

conYNB.Open();
cmdYNB.ExecuteNonQuery();
MessageBox.Show("A table named Cars has been
created");
}

using (SqlConnection conYNB =


new SqlConnection("Data Source=(local); " +
"Database='BethesdaCarRental1'; " +
"Integrated Security='SSPI';"))
{
string strCreateTable = "CREATE TABLE RentalOrders( "
+
"RentalOrderID int identity(1, 1) NOT NULL, "
+
"DateProcessed datetime, " +
"EmployeeID int Constraint " +
"FK_Employees References " +
"Employees(EmployeeID) NOT NULL, " +
"EmployeeName varchar(80), " +
"CustomerID int Constraint " +
"FK_Customers References " +
"Customers(CustomerID) NOT NULL, "
+
"CustomerName varchar(80), " +
"CustomerAddress varchar(100), " +
"CustomerCity varchar(50), " +
"CustomerState varchar(50), " +
"CustomerZIPCode varchar(20), " +
"CarID int Constraint " +
"FK_Cars References Cars(CarID) NOT
NULL, " +
"CarMake varchar(50), " +
"CarModel varchar(50), " +
"CarYear smallint, " +
"CarCondition varchar(50), " +
"TankLevel varchar(40), " +
"MileageStart int, " +
"MileageEnd int, " +
"RentStartDate datetime, " +
"RentEndDate datetime, " +
"Days int, " +
"RateApplied money, " +
"SubTotal money, " +
"TaxRate decimal(6, 2), " +
"TaxAmount money, " +
"OrderTotal money, " +
"OrderStatus varchar(50), " +
"CONSTRAINT PK_RentalOrder " +
"PRIMARY KEY (RentalOrderID));";

SqlCommand cmdYNB = new SqlCommand(strCreateTable,


conYNB);

conYNB.Open();
cmdYNB.ExecuteNonQuery();
MessageBox.Show("A table named RentalOrder has been
created");
}
}
}
}
6. Execute the application
7. Close the form and return to your programming environment
8. In the source file, delete the whole content of the Load event
9. In the Server Explorer, right-click the Data Connections node and click Add Connection
10. In the Server Name combo box of the Add Connection dialog box, type (local) or select the nam
server
11. In the Select Or Enter A Database Name combo box, select BethesdaCarRental1 and click Test Co
12. Click OK twice

Diagrams
A diagram is a window that visually displays the relationships among the tables of a database. To
diagram:

1. In the Object Explorer in Microsoft SQL Server Management Studio or in the Server Explorer in M
Visual Studio, in the database node, you can click Database Diagrams
2. A dialog box will inform you that this database does not have a diagram. Read the message and
3. Right-click Database Diagrams and click New Database Diagram
4. In the Add Table dialog box, click each table and click the Add.
Alternatively, you can double-click a table to add it
5. In the Add Table dialog box, you can click Close.
On the toolbar, you can click the Zoom button and select a larger or smaller value.
To move a table, you can drag its title bar. Here is an example:

6. To establish a relationship, you can click the gray box on the left of any column from the parent t
drop it on any column in the child table. A better way is to click gray box of the primary key colu
the parent table, drag that box then drop it on the foreign key column of the child table. Here is
example:

7. A Tables and Columns dialog box would come up. It would display the column that was dragged a
column on which you dropped.
If you had selected just any column, it would show but it may not be the one you wanted to drag
it may not be the actual column that is supposed to manage the relationship.
Regardless, under Primary Key Table, you should select the parent table
8. Under the parent table, select its primary column
9. Under Foreign Table, select the foreign key column. Here is an example:

10. Once you are ready, click OK. A link would be created between the tables

11. In the same way, you can create other relationships.


When you have finished, you can save and close the database

Practical Learning: Creating a Diagram


1. In the Server Explorer, expand the BethesdaCarRental1 node and click the + button of the Datab
Diagrams node
2. A dialog box will inform you that this database does not have a diagram. Read the message and
3. Right-click Database Diagrams and click Add New Diagram
4. In the Add Table dialog box, click Employees and click Add
5. Double-click Cars to add it
6. In the same way, add the Customers and the RentalOrders tables
7. On the Add Table dialog box, click Close.
Notice that, based on how we created the database and its objects, the relationships have been c
already:

8. To save the diagram, on the Standard toolbar, click Save


9. Set its name to dgmBethesdaCarRental and click OK
10. Close the window

Referential Integrity
On a typical database, information comes and goes. For a car rental company, car information is cr
deleted on a regular basis. When information about a car is deleted, there is concern about the ren
related to that car. Referential integrity allows you to manage these aspects of a database. You need
sure that when data is deleted from a parent table, the child tables are notified and their related re
deleted also. When information is changed on a parent table, the related information is changed in
tables.

To manage referential integrity, you use the Foreign Key Relationships dialog box. You can access it
design view of a table or from the diagram window.

Practical Learning: Managing Referential Integrity


1. In the Server Explorer, expand the Tables node under BethesdaCarRental1.
Right-click RentalOrders and click Open Table Definition
2. Right-click in the table and click Relationships
3. Under Selected Relationships, click FK_Customers. In the right section, expand INSERT And UPDA
Specification
4. Click Delete Rule. In its combo box, select Cascade
5. Click Update Rule. In its combo box, select Cascade:

6. In the same way, specify the following

Foreign Key Delete Rule Update Rule


FK_Cars Cascade Cascade
FK_Customers Cascade Cascade
FK_Employees Cascade Cascade

7. Click Close
8. Save and close the table

Published on Thursday 10 January 2008

Data Joins: Cross and Inner Joins


Introduction

When studying data relationships, we saw the role of the primary and
foreign keys in maintaining the exchange of information between two tables.
This technique of linking tables plays a major part when creating a join. It
allows you to decide whether you want to include all records or only isolate
some of them. To respect the direction of a relationship between two tables
as it is applied to a query, Transact-SQL supports three types of joins.

Cross Joins
A cross join creates a list of all records from both tables as follows: the first record from the parent t
each record from the child table, then the second record from the parent table is associated to e
child table, and so on. In this case also, there is no need of a common column between both tables.
will not use the ON clause.

To create a cross join, you can replace the TypeOfJoin factor of our formula with CROSS JOIN or CR
Here is an example:

SELECT Persons.PersonID, Persons.FirstName, Persons.LastName,


Sexes.SexID, Sexes.Sex
FROM Persons
CROSS JOIN Sexes
GO

If you are working visually on a table, by default, after you have just added a table to another one (if
already established between both tables), the query would be automatically made a cross join. All y
select the needed columns. After selecting the columns, you can execute the query to see the result:
Inner Joins
Imagine you have two tables that can be linked through one's primary key and another's foreign key.
Notice that some records in the Persons table do not have an entry for the SexID column and were m
the database engine. When creating a query of records of the Persons table, if you want your list to
that have an entry, you can create it as inner join.

By default, when creating a new query, if a relationship was already established between both tables
an inner join. If there was no relationship explicitly established between both tables, you would h
statement. Consider the following:
Notice that, because no relationship was previously established between both tables, the join is crosse

To create an inner join, you have two options. You can drag the primary key from the parent table
foreign key in the child table. Here is an example:
Alternatively, you can edit the SQL statement manually to make it an inner join. To do this, you
TypeOfJoin factor of our formula with the expression INNER JOIN. Here is an example:

SELECT Persons.PersonID, Persons.FirstName, Persons.LastName, Persons.SexID,


Sexes.SexID AS [Sex ID], Sexes.Sex
FROM Persons INNER JOIN Sexes ON Persons.SexID = Sexes.SexID

After creating the join, in the Diagram section, a line would be created to join the tables. You can the
to see the result. This would produce:
We mentioned earlier that you could include all columns in the query. In our result, since we are mo
Sex of each Persons record, we would not need the SexID column from the Sexes table. Here is an ex
As mentioned earlier, notice that the result includes only records that have an entry (a non-NULL
foreign key column of the Persons table.

An alternative to the INNER JOIN expression is to simply type JOIN. Here is an example:

SELECT Persons.PersonID, Persons.FirstName, Persons.LastName,


Sexes.Sex
FROM Persons
JOIN Sexes
ON Persons.SexID = Sexes.SexID

To destroy a join between two tables, if you are working in the Table window, you can right-click th
tables and click Remove. In SQL, you must modify the expressions that make up the join (the
expressions).

Practical Learning: Creating an Inner Join


1. To create an inner join, from the PropertyTypes table, drag PropertyTypeID and drop it on the Pr
of the Properties table:

2. Release the mouse


3. On the tables, select the following fields: PropertyType, City, Bedrooms, Bathrooms, YearBuilt,
4. On the Query Designer toolbar, click the Execute button to see the result
5. Click OK
6. Click Finish
7. Access the form and click the data grid view
8. In the Properties window, set its DataSource to None and set it again to bsProperties
9. Execute the application to see the result

10. Close the form and return to your programming environment

Data Joins: Outer Joins


Introduction

Instead of showing only records that have entries in the child table, you
may want your query to include all records, including those that are null. To
get this result, you would create an outer join. You have three options.

Left Outer Joins


A left outer join produces all records of the child table, also called the right
table. The records of the child table that do not have an entry in the foreign
key column are marked as NULL.

To create a left outer join, if you are working in the Table window, in the Diagram section, right-clic
the tables and click the option that would select all records from the child table (in this case, that
Rows From Persons):

Alternatively, you can replace the TypeOfJoin factor of our formula with either LEFT JOIN or LEFT O
an example:

SELECT Persons.PersonID, Persons.FirstName, Persons.LastName,


Sexes.SexID, Sexes.Sex
FROM Persons
LEFT OUTER JOIN Sexes
ON Persons.SexID = Sexes.SexID
GO

In both cases, the button in the middle of the line would be added an arrow that points to the parent
execute the query to see the result. Here is an example:
Notice that the result includes all records of the Persons (also called the right) table and the records
entry in the SexID column of the Persons (the right) table are marked with NULL.

Right Outer Joins


A right outer join considers all records from the parent table and finds a matching record in the child
starts with the first record of the parent table (in this case the Sexes table) and shows each record o
this case the Persons table) that has a corresponding entry. This means that, in our example, a right o
create a list of the Persons records that have a 1 (Female) value for the SexID column. After the fi
outer join moves to the second record, and so on, each time listing the records of the child
corresponding entry for the primary key of the parent table.

To visually create a right outer join in the Table window, after establishing a join between both
previously created a left outer join, you should remove it by right-clicking the line between the tabl
second option under Remove. Then, you can right-click the line that joins them and click the option
records from the parent table. In our example, you would click Select All Rows From Sexes.

To create a right outer join in SQL, you can replace the TypeOfJoin factor of our formula with RIG
OUTER JOIN. Here is an example:

SELECT Persons.PersonID, Persons.FirstName, Persons.LastName,


Sexes.SexID, Sexes.Sex
FROM Persons
RIGHT OUTER JOIN Sexes
ON Persons.SexID = Sexes.SexID
GO

In both cases, the button on the joining line between the tables would have an arrow that points to t
can then run the query. Here is an example:
Notice that the query result starts with the first record of the parent table, also called the left table (in
table), and lists the records of the child table, also called the right table (in this case the Persons t
entry corresponding to that first record. Then it moves to the next SexID value. Also, notice that
records in the Sex.

Practical Learning: Getting Non-NULL Records


1. In the Data Source window, right-click dsAltairRealtors and click Edit Dataset with Designer
2. In the designer, right-click the title bar of the Properties table and click Configure...
3. In the TableAdapter Configuation Wizard, click Query Builder...
4. To get a list of only properties whose types are known, right-click the line between the tables and
rows from PropertyTypes
5. Right-click anywhere in the window and click Execute SQL
6. Notice that the result is the list of tables in order by types (condos, single families, and town hom
7. Uncheck all columns
Full Outer Joins
A full outer join produces all records from both the parent and the child tables. If a record from one ta
value in the other value, the value of that record is marked as NULL.

To visually create a full outer join, in the Table window, right-click the line between the tables and
under Remove so that both would be checked. To create a full outer join in SQL, replace the Type
formula with FULL JOIN or FULL OUTER JOIN. Here is an example:

SELECT Persons.PersonID, Persons.FirstName, Persons.LastName,


Sexes.SexID, Sexes.Sex
FROM Persons
FULL OUTER JOIN Sexes
ON Persons.SexID = Sexes.SexID
GO

The button on the line between the tables would now appear as a square. You can then execute th
example:
Just as we have involved only two tables in our joins so far, you can create a join that includes many t

Joins and Data Analysis


Introduction

As demonstrated so far and in previous lessons, the main reason for


creating queries is to isolate records. This is done using conditions and
criteria. Joins enhance this capability because they allow you to consider
records from different tables and include them in a common SQL statement.

In the joins we have created so far, we considered all records and let the
database engine list them using only the rules of joins built-in the SQL. To
make such a list more useful or restrictive, you can pose your own
conditions that should be respected to isolate records like a funnel. As done
in previous lessons, to include a criterion in a SELECT statement, you can
create a WHERE clause.

Using Criteria
To create a criterion in a query you create from the table view in the Microsoft SQL Server Mana
Microsoft Visual Studio, first select a column to display it in the Grid section. Just as reviewed in t
when creating a query, to specify a criterion, in the Criteria box corresponding to the column, type
any of the operators we reviewed in previous lessons. Here is an example:

SELECT Persons.PersonID, Persons.FirstName, Persons.LastName,


Sexes.SexID, Sexes.Sex
FROM Persons LEFT OUTER JOIN
Sexes ON Persons.SexID = Sexes.SexID
WHERE Sexes.Sex = 'female'

This would produce:


Practical Learning: Analyzing Data Involving Joins
1. Right-click an area of the Query Builder window and click Add Table
2. In the Add Table dialog box, double-click Conditions and click Close
3. Drag ConditionID from the Conditions table and drop it on ConditionID from the Properties table
4. Click the check boxes of the following columns PropertyType, City, State, Bedrooms, Bathrooms,
Condition, and MarketValue
5. Right-click the window and click Execute SQL
6. Click OK and click Finish
7. On the form, click the data grid view
8. In the Properties window, set its DataSource to None and set it again to bsProperties
9. On the form, double-click the Show combo box and implement the event as follows:

private void cbxShow_SelectedIndexChanged(object s}er, EventArgs e)


{
if (cbxShow.SelectedIndex == 1)
bsProperties.Filter = "PropertyType = 'Townhouse'";
else if (cbxShow.SelectedIndex == 2)
bsProperties.Filter = "PropertyType = 'Condominium'";
else if (cbxShow.SelectedIndex == 3)
bsProperties.Filter = "PropertyType = 'Single Family'";
else
bsProperties.Filter = "";
}

10. Execute the application to see the result


11. Close the form and return to your programming environment

Introduction
This is an example of binding data of a table to a data grid view. Of course, you must have a databas

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace DataGridViewBinding
{
public partial class Exercise : Form
{
public Exercise()
{
InitializeComponent();
}

private void btnLoad_Click(object sender, EventArgs e)


{
using (SqlConnection conExercise =
new SqlConnection("Data Source=(local);" +
"Database='Exercise';" +
"Integrated Security=SSPI;"))
{
string strExercise = "SELECT * FROM Employees";
SqlCommand cmdExercise = new SqlCommand(strExercise, conExercise);
SqlDataAdapter sdaExercise = new SqlDataAdapter(cmdExercise);
DataSet dsExercise = new DataSet("ExerciseSet");

sdaExercise.Fill(dsExercise);
dgvExercise.DataSource = dsExercise;
dgvExercise.DataMember = dsExercise.Tables[0].TableName;
}
}
}
}

Elementary Addition

Introduction
This exercise applies the characteristics of a label to assist you with
performing elementary additions.
In this application, two numbers are selected randomly. Each number is less
than 100. After the form displays these two numbers, the user (the student)
is asked to add them and enter the result. The user/student can then click
Check to check the result.

Windows Controls:

• Label
• Dialog Box

Practical Learning: Introducing Text Boxes


1. Create a Window Forms Application named ElementaryAddition2
2. Design the form as follows:

Additional
Control Text Name TextAlign Font
Properties
Name: Tahoma
AutoSize: True
Label 00 lblOperand1 Center Size: 48
ForeColor: Blue
Bold: True
Name: Arial
AutoSize: True
Label + Center Size: 50
ForeColor: Maroon
Bold: True
Name: Tahoma
AutoSize: True
Label 00 lblOperand2 Center Size: 48
ForeColor: Blue
Bold: True
Name: Arial
AutoSize: True
Label = Center Size: 50
ForeColor: Green
Bold: True
Name: Tahoma
TextBox 000 txtResult Center Size: 48
Bold: True
Label New lblNewOperation Center Name: Tahoma, AutoSize: True
BorderStyle:
Fixed3D
Operation Size: 28 Bold: True
ForeColor: White
BackColor:Maroon
AutoSize: True
BorderStyle:
Name: Tahoma,
Label Check lblCheckAnswer Center Fixed3D
Size: 28 Bold: True
ForeColor: White
BackColor:Maroon
AutoSize: True
Name: Tahoma,
Label Quit lblQuit Center BorderStyle:
Size: 28 Bold: True
FixedSingle

3. Double-click the New Operation label and implement its event as follows:

private void lblNewOperation_Click(object sender,


EventArgs e)
{
int operand1;
int operand2;

Random rnd = new Random();

operand1 = rnd.Next(99);
operand2 = rnd.Next(99);
int result = operand1 + operand2;

lblOperand1.Text = operand1.ToString();
lblOperand2.Text = operand2.ToString();
txtResult.Text = "";
txtResult.Focus();
}
4. Return to the form and double-click the Check label
5. Implement its event as follows:

private void lblCheckAnswer_Click(object sender,


EventArgs e)
{
int Operand1 = 0;
int Operand2 = 0;
int Result = 0;

try
{
Operand1 = int.Parse(lblOperand1.Text);
}
catch (FormatException)
{
MessageBox.Show("Invalid Value");
}

try
{
Operand2 = int.Parse(lblOperand2.Text);
}
catch (FormatException)
{
MessageBox.Show("Invalid Value");
}

try
{
Result = int.Parse(txtResult.Text);
}
catch (FormatException)
{
MessageBox.Show("Invalid Answer");
}

if (Result == (Operand1 + Operand2))


MessageBox.Show("WOW - Good Answer");
else
MessageBox.Show("PSSST - Wrong Answer");

lblNewOperation_Click(sender, e);
}
6. Return to the form and double-click Quit
7. Implement its event as follows:

private void lblQuit_Click(object sender, EventArgs e)


{
Close();
}
8. Execute the application and test it
9. Click the Close button to close the form and return to your programming environment

Example Application: Car Inventory


Introduction
This application explores the characteristics of a track bar, also called a
slider control. It uses a class that holds various pieces of information about
cars. One of the track bars allows the user to navigate from one car to
another. When the position of that track bar changes, the compiler refers to
an array of car to locate the object to display. When this happens, the
default picture of the car also displays.

A vertical track bar allows the user to show other pictures of a car, in case
other pictures are available.

Windows Controls:

• Label
• Button
• Track Bar
• Group Box
• Picture Box

Practical Learning: Introducing Track Bars


1. Start a new Windows Application named CarInventory1
2. Copy the pictures of the cars and paste them in the
CarInventory1\CarInventory1\bin\debug folder of the current project
3. On the main menu, click Project -> Add Class...
4. Set the Name to Car and click Add
5. Create the following members of the class:
using System;

namespace CarInventory1
{
public class Car
{
public string Make;
public string Model;
public int Year;
public double Price;
public string Picture;
}
}
6. Save all
1. Design the form as follows:

Control Text Name Additional Properties


GroupBox Car Description
Label Make:
TextBox Honda txtMake
Label Model:
TextBox txtModel
Label Year:
TextBox txtYear TextAlign: Right
Label Price:
TextBox txtPrice TextAlign: Right
PictureBox pbxCarImage SizeMode: CenterImage
TrackBar tbrImages Orientation: Vertical
TrackBar tbrReview
Button Close btnClose
2. Execute the application to test the form
3. Close the form and return to your programming environment

The Value of a Track Bar


As mentioned already, to use the track bar, the user must change the position of the thumb. To
change this position, the user can drag the thumb, click the slider line, press one of the arrow
keys, or press the Page Up or Page Down keys. As the user drags the thumb, the control fires a
Scroll event. This event is of type EventArgs. Because this is the default event of the control,
to generate its skeleton code, you can double-click the track bar on the control

When the user drags the thumb, the control holds a new value known as the Value property.
You also can assign a value to this property to change the position of the thumb. The value of
the Value property must be an integer. After the user has changed it, to know the value of the
track bar, you can access its Value property. Here is an example:

private void InitializeComponent()


{
tbrSlider = new TrackBar();
tbrSlider.Location = new Point(12, 12);
tbrSlider.Width = 180;

tbrSlider.Value = 6;

Controls.Add(tbrSlider);
}

This would produce:

Practical Learning: Generating the Scroll Event


1. On the form, double-click the bottom track bar
2. Return to the form and double-click the right track bar
3. Return to the form

The Maximum and the Minimum Values


However the user moves the thumb, it must assume a value between the limits allowed on the
control. The Minimum property is the lowest value that the thumb can assume within the
track. The Maximum value controls the opposite. The user is allowed to slide only between
these two values. These two properties are set in the Properties window using their respective
fields. By default, the minimum value is set to 0 and the maximum is 10. To change the
minimum or maximum values programmatically, assign the desired value to the appropriate
property. Here is an example:

private void InitializeComponent()


{
tbrSlider = new TrackBar();
tbrSlider.Location = new Point(12, 12);
tbrSlider.Width = 480;

tbrSlider.Minimum = 8;
tbrSlider.Maximum = 140;

tbrSlider.Value = 86;

Controls.Add(tbrSlider);
}

This would produce:

You can also set the minimum and the maximum values by calling the TrackBar.SetRange()
method. Its syntax is:

public void SetRange(int minimum, int maximum);

The first argument is the same as the Minimum property and the second argument is the
same as the Maximum property. Here is an example:

private void InitializeComponent()


{
tbrSlider = new TrackBar();
tbrSlider.Location = new Point(12, 12);
tbrSlider.Width = 480;

tbrSlider.SetRange(8, 140);

tbrSlider.Value = 86;

Controls.Add(tbrSlider);
}

Always make sure that the minimum value is lower than the maximum. This safe measure will
allow you to better control the current value of the control. At design time, if you set the
Minimum property to a value higher than that of the Maximum, for example setting
Minimum to 66 while Maximum=10, the value of the Maximum would be set to that of the
Minimum. In this case, both properties would have the same value. This makes the control
unusable: if the Minimum and the Maximum properties hold the same values, the user cannot
move the thumb. In the same way, at run time, avoid assigning unpractical values to these
properties.

The Ticks of a Track Bar


A track bar is equipped with small bars “|” that serve as indicators of the position occupied by
the thumb. These bars are called ticks. The ticks are positioned at same distances from each
other. The number of ticks available on a track bar, or the number of ticks you can see, depend
on the difference between the Minimum and the Maximum values The higher the Maximum -
Minimum difference, the more ticks available. The lower this value, the fewer the ticks but this
should not be the reason you use a lower Minimum or a higher Maximum.

The Tick Frequency


If the difference between the Maximum and the Minimum properties causes the control to
display too many ticks. Consider the following example:

private void InitializeComponent()


{
tbrSlider = new TrackBar();
tbrSlider.Location = new Point(12, 12);
tbrSlider.Width = 400;
tbrSlider.SetRange(8, 255);
tbrSlider.Value = 125;

Controls.Add(tbrSlider);
}

When this happens, you can reduce the number of ticks. This is done using the TickFrequency
property. Here is an example:

private void InitializeComponent()


{
tbrSlider = new TrackBar();
tbrSlider.Location = new Point(12, 12);
tbrSlider.Width = 400;
tbrSlider.SetRange(8, 255);
tbrSlider.Value = 125;

tbrSlider.TickFrequency = 10;

Controls.Add(tbrSlider);
}

This would produce:

The Tick Style


The thumb’s visual display appears as a small standing pentagon with two straight borders. Its
appearance is set using the TickStyle property which is based on the TickStyle enumeration.
When you add a new TrackBar control to a form, it is horizontally oriented, the thumb points
down, the tick marks are positioned under the sliding field. In this setting, the TickStyle
property is set to BottomRight. To place the tick marks above the sliding field, change the
value of the TickStyle property to TopLeft; this also has the effect of reversing the direction
of the slider. Here is an example:

private void InitializeComponent()


{
tbrSlider = new TrackBar();
tbrSlider.Location = new Point(12, 12);
tbrSlider.Width = 400;
tbrSlider.SetRange(8, 255);
tbrSlider.Value = 125;
tbrSlider.TickFrequency = 10;

tbrSlider.TickStyle = TickStyle.TopLeft;

Controls.Add(tbrSlider);
}

This would produce:

As a third option, you can have the tick marks on both sides of the slider. To get this, set the
TickStyle property to Both. With this value, the thumb becomes a small rectangle (changing
from its pentagon shape):

Practical Learning: Setting the Tick Style


1. On the form, click the right track bar
2. In the Properties window, click TickStyle and select Both from its combo box
3. On the form, click the bottom track bar
4. In the Properties window, click TickStyle and select TopLeft from its combo box
5. Save all

The Small Change


When the user presses one of the arrow keys, the thumb moves by one tick. This unit is known
as the SmallChange property. If you want the thumb to move by more than one tick, you can
assign the desired value to this property. Alternatively, you can calculate a fraction of the
difference between the Minimum and the Maximum values then use it as the SmallChange.

The Large Change


When the user presses either the Page Up (PgUp) or the Page Down (PgDn) keys, the thumb
moves by a value represented by the LargeChange property. If the default value of this
property is not convenient for your application, you can change it to a new desired value or you
can use a fraction of the difference between the Minimum and the Maximum properties then
use it as the LargeChange.

Practical Learning: Using a Track Bar


1. Double-click an unoccupied of the form
2. Return to the form and double-click the Close button
3. Change the file as follows:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace CarInventory1
{
public partial class Form1 : Form
{
int ReviewPosition;

Car[] Cars = new Car[15];

// We will not use the commented arrays.


// They are only mentioned here for reference
string[] pictures0;
string[] pictures1 = new string[5];
string[] pictures2 = new string[3];
//string[] pictures3 = new string[0];
string[] pictures4 = new string[3];
string[] pictures5 = new string[3];
string[] pictures6 = new string[3];
//string[] pictures7 = new string[0];
//string[] pictures8 = new string[0];
//string[] pictures9 = new string[0];
string[] pictures10 = new string[3];
string[] pictures11 = new string[4];
//string[] pictures12 = new string[0];
string[] pictures13 = new string[7];
string[] pictures14 = new string[2];

public Form1()
{
InitializeComponent();
}

private void tbrReview_Scroll(object sender, EventArgs e)


{
// Get the index of the current value of the track bar
ReviewPosition = tbrReview.Value;

// Based on the current index, retrieve the values of the


// current car and assign each to the corresponding
control
txtMake.Text = Cars[ReviewPosition].Make;
txtModel.Text = Cars[ReviewPosition].Model;
txtYear.Text = Cars[ReviewPosition].Year.ToString();
txtPrice.Text = Cars[ReviewPosition].Price.ToString();
pbxCarImage.Image =
Image.FromFile(Cars[ReviewPosition].Picture);

// To make the right track bar aware of the number


// of pictures of each car, set its maximum property
// according to the number of pictures (- 1)
switch (ReviewPosition)
{
case 0:
tbrImages.Maximum = 8;
break;
case 1:
tbrImages.Maximum = 5;
break;
case 2:
tbrImages.Maximum = 3;
break;
case 3:
tbrImages.Maximum = 0;
break;
case 4:
tbrImages.Maximum = 3;
break;
case 5:
tbrImages.Maximum = 3;
break;
case 6:
tbrImages.Maximum = 3;
break;
case 7:
tbrImages.Maximum = 0;
break;
case 8:
tbrImages.Maximum = 0;
break;
case 9:
tbrImages.Maximum = 0;
break;
case 10:
tbrImages.Maximum = 3;
break;
case 11:
tbrImages.Maximum = 4;
break;
case 12:
tbrImages.Maximum = 0;
break;
case 13:
tbrImages.Maximum = 7;
break;
case 14:
tbrImages.Maximum = 1;
break;
default:
break;
}

tbrImages.Value = 0;
}

private void tbrImages_Scroll(object sender, EventArgs e)


{
// Check the position of the bottom track bar
// Then, use the value of the right track bar
// to locate the right picture
switch (ReviewPosition)
{
case 0:
pbxCarImage.Image =
Image.FromFile(pictures0[tbrImages.Value]);
break;
case 1:
pbxCarImage.Image =
Image.FromFile(pictures1[tbrImages.Value]);
break;
case 2:
pbxCarImage.Image =
Image.FromFile(pictures2[tbrImages.Value]);
break;
case 4:
pbxCarImage.Image =
Image.FromFile(pictures4[tbrImages.Value]);
break;
case 5:
pbxCarImage.Image =
Image.FromFile(pictures5[tbrImages.Value]);
break;
case 6:
pbxCarImage.Image =
Image.FromFile(pictures6[tbrImages.Value]);
break;
case 10:
pbxCarImage.Image =
Image.FromFile(pictures10[tbrImages.Value]);
break;
case 11:
pbxCarImage.Image =
Image.FromFile(pictures11[tbrImages.Value]);
break;
case 13:
pbxCarImage.Image =
Image.FromFile(pictures13[tbrImages.Value]);
break;
case 14:
pbxCarImage.Image =
Image.FromFile(pictures14[tbrImages.Value]);
break;
default:
break;
}
}

private void Form1_Load(object sender, EventArgs e)


{
// Create the list of cars
Cars[0] = new Car();
Cars[0].Make = "BMW";
Cars[0].Model = "335i";
Cars[0].Year = 2007;
Cars[0].Price = 42580;
Cars[0].Picture = "335iA.gif";

Cars[1] = new Car();


Cars[1].Make = "Honda";
Cars[1].Model = "Accord";
Cars[1].Year = 2007;
Cars[1].Price = 24550;
Cars[1].Picture = "Accord1.gif";

Cars[2] = new Car();


Cars[2].Make = "Chevrolet";
Cars[2].Model = "Avalanche";
Cars[2].Year = 2007;
Cars[2].Price = 36880;
Cars[2].Picture = "Avalanche1.gif";

Cars[3] = new Car();


Cars[3].Make = "Volvo";
Cars[3].Model = "C70";
Cars[3].Year = 1997;
Cars[3].Price = 42320;
Cars[3].Picture = "C70.gif";

Cars[4] = new Car();


Cars[4].Make = "Land Rover";
Cars[4].Model = "LR3";
Cars[4].Year = 2007;
Cars[4].Price = 46245;
Cars[4].Picture = "LR3a.gif";

Cars[5] = new Car();


Cars[5].Make = "Honda";
Cars[5].Model = "Civic";
Cars[5].Year = 2000;
Cars[5].Price = 22665;
Cars[5].Picture = "Civic1.gif";

Cars[6] = new Car();


Cars[6].Make = "Mazda";
Cars[6].Model = "Mazda5";
Cars[6].Year = 2007;
Cars[6].Price = 20845;
Cars[6].Picture = "Mazda5a.gif";

Cars[7] = new Car();


Cars[7].Make = "Ford";
Cars[7].Model = "Escape";
Cars[7].Year = 1997;
Cars[7].Price = 22445;
Cars[7].Picture = "Escape.gif";

Cars[8] = new Car();


Cars[8].Make = "Acura";
Cars[8].Model = "TSX";
Cars[8].Year = 2006;
Cars[8].Price = 26445;
Cars[8].Picture = "TSX.gif";

Cars[9] = new Car();


Cars[9].Make = "Mazda";
Cars[9].Model = "Miata";
Cars[9].Year = 2008;
Cars[9].Price = 24180;
Cars[9].Picture = "Miata.gif";

Cars[10] = new Car();


Cars[10].Make = "Ford";
Cars[10].Model = "F-150";
Cars[10].Year = 2006;
Cars[10].Price = 20475;
Cars[10].Picture = "F150a.gif";

Cars[11] = new Car();


Cars[11].Make = "Volvo";
Cars[11].Model = "S40";
Cars[11].Year = 2008;
Cars[11].Price = 25285;
Cars[11].Picture = "S40a.gif";

Cars[12] = new Car();


Cars[12].Make = "BMW";
Cars[12].Model = "750i";
Cars[12].Year = 2007;
Cars[12].Price = 88925;
Cars[12].Picture = "750Li.gif";

Cars[13] = new Car();


Cars[13].Make = "Buick";
Cars[13].Model = "LaCrosse";
Cars[13].Year = 2002;
Cars[13].Price = 28685;
Cars[13].Picture = "LaCrosse1.gif";

Cars[14] = new Car();


Cars[14].Make = "Ford";
Cars[14].Model = "E-150 XL";
Cars[14].Year = 2002;
Cars[14].Price = 26660;
Cars[14].Picture = "E150XLa.gif";

// Create the list of pictures for each car


pictures0 = new string[9]
{
"335iA.gif", "335iB.gif", "335iC.gif",
"335iD.gif", "335iE.gif", "335iF.gif",
"335iG.gif", "335iH.gif", "335iI.gif"
};
pictures1 = new string[]
{
"Accord1.gif", "Accord2.gif", "Accord3.gif",
"Accord4.gif", "Accord5.gif", "Accord6.gif"
};
pictures2 = new string[]
{
"Avalanche1.gif", "Avalanche2.gif",
"Avalanche3.gif", "Avalanche4.gif"
};
pictures4 = new string[]
{
"LR3a.gif", "LR3b.gif",
"LR3b.gif", "LR3d.gif"
};
pictures5 = new string[]
{
"Civic1.gif", "Civic2.gif",
"Civic3.gif", "Civic4.gif"
};
pictures6 = new string[]
{
"Mazda5a.gif", "Mazda5b.gif",
"Mazda5c.gif", "Mazda5d.gif"
};
pictures10 = new string[]
{
"F150a.gif", "F150b.gif",
"F150c.gif", "F150d.gif"
};
pictures11 = new string[]
{
"S40a.gif", "S40b.gif",
"S40c.gif", "S40d.gif", "S40e.gif"
};
pictures13 = new string[]
{
"LaCrosse1.gif", "LaCrosse2.gif", "LaCrosse3.gif",
"LaCrosse4.gif", "LaCrosse5.gif", "LaCrosse6.gif",
"LaCrosse7.gif", "LaCrosse8.gif"
};
pictures14 = new string[]
{
"E150XLa.gif", "E150XLb.gif"
};

// Call the Scroll event of the bottom track bar


// as if it had been scrolled
tbrReview_Scroll(sender, e);
}

private void btnClose_Click(object sender, EventArgs e)


{
// Close the application
Close();
}
}
}
4. Execute the application and test the track bar:
5. Close the form and return to your programming environment
Download

Example Solutions: The Time Sheet


Introduction
A time sheet is a list that holds the time values worked by an employee or a
contractor over a time period. In many companies, employees or
contractors are usually asked to use a piece of paper on which they should
record the necessary information for one or two weeks worth of the time
they spent performing a duty. Nowadays, most companies use an
electronic

means of collecting the time. In an Intranet, employees may have to access an


application from a shared drive, open the appropriate document, fill out their time
sheet, and submit it.

A Paper Time Sheet


A paper time sheet is a physical list of values on a piece of paper. An employee would usually
keep the paper that he or she can pick up at any time and modify it various times during the
time period. If people from the accounting or payroll department wants to examine the time
sheet of one particular employee, they would have to call the employee and request it. This is
can be difficult or problematic if the employee and the company's accounting are not physically
close, which is not uncommon nowadays (it is not surprising anymore for somebody located in
New York to work for an employer who resides in San Francisco, or for a contractor in Adelaide
to work for a company in Sydney). When the time period is over, such as at the end of the week
or at the end of the two-week period, the employee can submit the time sheet. The time sheet
is then sent to the accounting or payroll department.

An Electronic Time Sheet


An electronic time sheet is accessed using a computer. Usually, all employees time sheets are
stored somewhere in a database on a computer. As stated earlier, an employee can access it
any time, so can the accounting or payroll department. This means that, at any time, a
supervisor can check the time sheet, for any reason. To make this possible, an application,
namely a database is created, stored somewhere in a common computer such as a server, and
given access to those who can use it.

One of the advantages of using paper time sheet is that, since the employee keeps the time
sheet, there is no risk of having a duplicate time sheet. On the other hand, if you create an
electronic table of time sheets, when an employee who wants to fill out his or her time sheet
opens it, you need to make sure that the right time sheet is opened. In the same way, if
somebody from the payroll department wants to check one particular employee's time sheet,
you need to make it possible and easy to locate the right time sheet.

In the solution we are going to apply, we will create a table of employees and the time sheet
they can fill out. In our time sheet, we will create a certain column, named TimeSheetCode, that
will hold a unique number. We will come back to the role of this column.

Practical Learning: Introducing the Time Sheet


1. If you want to practice with this exercise, start Microsoft SQL Server with the SQL Server
Management Studio and connect to the server
2. On the main menu, click File -> New -> Query With Current Connection and type the
following:

-- =============================================
-- Database: ynb1
-- For: Yugo National Bank
-- Author: FunctionX
-- Date Created: Monday 24 April 2007
-- =============================================
USE master
GO

-- Drop the database if it already exists


IF EXISTS (
SELECT name
FROM sys.databases
WHERE name = N'ynb1'
)
DROP DATABASE ynb1
GO
CREATE DATABASE ynb1
GO
-- =========================================
-- Database: ynb1
-- For: Yugo National Bank
-- Table: Employees
-- =========================================
USE ynb1;
GO
IF OBJECT_ID('dbo.Employees', 'U') IS NOT NULL
DROP TABLE dbo.Employees
GO
CREATE TABLE Employees
(
EmployeeID int Identity(1,1) NOT NULL,
EmployeeNumber varchar(20),
FirstName varchar(20) NULL,
LastName varchar(20) NOT NULL,
Title varchar(80) NULL,
HourlySalary smallmoney NULL,
CONSTRAINT PK_Employees PRIMARY KEY (EmployeeID)
);
GO

INSERT INTO Employees(EmployeeNumber, FirstName,


LastName, Title, HourlySalary)
VALUES('88024', 'Matthew',
'Larson', 'Account Manager' , 32.15);
GO
INSERT INTO Employees(EmployeeNumber, FirstName,
LastName, Title, HourlySalary)
VALUES('25711', 'Patricia',
'Katts', 'Regional Manager' , 42.15);
GO
INSERT INTO Employees(EmployeeNumber, FirstName,
LastName, Title, HourlySalary)
VALUES('20410', 'Helene',
'Boileau', 'Cashier' , 12.15);
GO
INSERT INTO Employees(EmployeeNumber, FirstName,
LastName, Title, HourlySalary)
VALUES('91272', 'Peter',
'Ulm', 'Head Cashier' , 22.15);
GO
INSERT INTO Employees(EmployeeNumber, FirstName,
LastName, Title, HourlySalary)
VALUES('29475', 'Victoria',
'Canston', 'Cashier' , 14.25);
GO
-- =========================================
-- Database: ynb1
-- For: Yugo National Bank
-- Table: TimeSheets
-- =========================================
IF OBJECT_ID('dbo.TimeSheets', 'U') IS NOT NULL
DROP TABLE dbo.TimeSheets
GO

CREATE TABLE dbo.TimeSheets


(
TimeSheetID int identity(1,1) NOT NULL,
EmployeeNumber varchar(5) NOT NULL,
StartDate datetime NOT NULL,
TimeSheetCode varchar(15),
Week1Monday varchar(6),
Week1Tuesday varchar(6),
Week1Wednesday varchar(6),
Week1Thursday varchar(6),
Week1Friday varchar(6),
Week1Saturday varchar(6),
Week1Sunday varchar(6),
Week2Monday varchar(6),
Week2Tuesday varchar(6),
Week2Wednesday varchar(6),
Week2Thursday varchar(6),
Week2Friday varchar(6),
Week2Saturday varchar(6),
Week2Sunday varchar(6),
Notes text,
CONSTRAINT PK_TimeSheets PRIMARY KEY(TimeSheetID)
)
GO
INSERT INTO TimeSheets(EmployeeNumber, StartDate, TimeSheetCode,
Week1Monday, Week1Tuesday, Week1Wednesday, Week1Thursday,
Week1Friday, Week1Saturday, Week1Sunday, Week2Monday,
Week2Tuesday, Week2Wednesday, Week2Thursday, Week2Friday,
Week2Saturday, Week2Sunday, Notes)
VALUES('20410', '2007/01/01', '2041020070101', '0.00', '8.50',
'9.50', '8.50', '9.00', '0.00', '0.00', '10.00', '9.50',
'8.50', '10.50', '9.00', '0.00', '0.00', 'Nothing to signal');
GO
INSERT INTO TimeSheets(EmployeeNumber, StartDate, TimeSheetCode,
Week1Monday, Week1Tuesday, Week1Wednesday, Week1Thursday,
Week1Friday, Week1Saturday, Week1Sunday, Week2Monday,
Week2Tuesday, Week2Wednesday, Week2Thursday, Week2Friday,
Week2Saturday, Week2Sunday)
VALUES('88024', '2007/01/01', '8802420070101', '0.00', '4.00',
'6.00', '5.50', '6.50', '0.00', '0.00', '4.00', '6.00',
'6.50', '4.00', '5.50', '0.00', '0.00');
GO
INSERT INTO TimeSheets(EmployeeNumber, StartDate, TimeSheetCode,
Week1Monday, Week1Tuesday, Week1Wednesday, Week1Thursday,
Week1Friday, Week1Saturday, Week1Sunday, Week2Monday,
Week2Tuesday, Week2Wednesday, Week2Thursday, Week2Friday,
Week2Saturday, Week2Sunday)
VALUES('94272', '2007/01/15', '9427220070115', '8.50', '8.00',
'9.00', '8.50', '9.50', '0.00', '0.00', '5.50', '6.50',
'4.50', '6.00', '4.00', '0.00', '0.00');
GO
INSERT INTO TimeSheets(EmployeeNumber, StartDate, TimeSheetCode,
Week1Monday, Week1Tuesday, Week1Wednesday, Week1Thursday,
Week1Friday, Week1Saturday, Week1Sunday, Week2Monday,
Week2Tuesday, Week2Wednesday, Week2Thursday, Week2Friday,
Week2Saturday, Week2Sunday)
VALUES('88024', '2007/01/15', '8802420070115', '8.00', '8.50',
'9.50', '9.50', '8.50', '0.00', '0.00', '10.00', '9.00',
'8.50', '8.00', '8.50', '0.00', '0.00');
GO
INSERT INTO TimeSheets(EmployeeNumber, StartDate, TimeSheetCode,
Week1Monday, Week1Tuesday, Week1Wednesday, Week1Thursday,
Week1Friday, Week1Saturday, Week1Sunday, Week2Monday,
Week2Tuesday, Week2Wednesday, Week2Thursday, Week2Friday,
Week2Saturday, Week2Sunday)
VALUES('20410', '2007/01/15', '2041020070115', '8.00', '8.00',
'6.00', '8.00', '6.00', '0.00', '0.00', '8.00', '8.00',
'8.00', '8.50', '8.00', '0.00', '0.00');
GO
3. Press F5 to execute the statement

Time Sheet Implementation


To address our problem of an electronic time, we will create a time sheet in which two pieces of
information are required: an employee's number and a starting period. After an employee has
opened a time sheet:

1. The employee must first provide an employee number, which we will check in the
Employees table. If the employee provides a valid employee number, we can continue with
the time sheet. If the employee number is invalid, we will let the user know and we cannot
continue with the time sheet
2. After the employee has provided a valid employee number, we will request the starting
period. After entering a (valid) date, we will check the time. If there is a record that holds
both the employee number and the start date, this means that the employee had
previously worked on a time sheet and we will open that existing time sheet.

After the the employee or contractor has entered a valid employee number and a start date, we
will create a number called a time sheet code, represented in the TimeSheet as the
TimeSheetCode column. This number is created as follows:

0000000000000

The first 5 digits represent the employee's number. The second 4 digits represent the year of
the start date. The next 2 digits represent the month, and the last 2 digits represent the day.
This number must be unique so that there would not be a duplicate number throughout the time
sheet.

To make sure the value of the TimeSheetCode is unique for each record, after the employee has
provided a valid employee number and a start date, we will create the time sheet code and
check if that number exists in the TimeSheet table already:

• If that number exists already, this means that the employee has previously worked on that
time sheet and he or she simply wants to verify or update it. We will then open the time
values for that record and let the user view or change it
• If there is no record with the specified time sheet code, we will conclude that the employee
is working on a new time sheet

Practical Learning: Implementing the Time Sheet


1. Start Microsoft Visual C# and create a Windows Forms Application named YNBTimeSheet1
2. Design the form as follows:

Other
Control Text Name
Properties
Label Employee #:
TextBox txtEmployeeNumber
Label . lblEmployeeNumber
Label Start Date:
DateTimePicker dtpStartDate
Label End Date:
Label . lblEndDate
Label Mon
Label Tue
Label Wed
Label Thu
Label Fri
Label Sat
Label Sun
Label Week 1:
TextAlign:
TextBox 0.00 txtWeek1Monday
Right
TextAlign:
TextBox 0.00 txtWeek1Tuesday
Right
TextAlign:
TextBox 0.00 txtWeek1Wednesday
Right
TextBox 0.00 txtWeek1Thursday TextAlign:
Right
TextAlign:
TextBox 0.00 txtWeek1Friday
Right
TextAlign:
TextBox 0.00 txtWeek1Saturday
Right
TextAlign:
TextBox 0.00 txtWeek1Sunday
Right
Label Week 2:
TextAlign:
TextBox 0.00 txtWeek2Monday
Right
TextAlign:
TextBox 0.00 txtWeek2Tuesday
Right
TextAlign:
TextBox 0.00 txtWeek2Wednesday
Right
TextAlign:
TextBox 0.00 txtWeek2Thursday
Right
TextAlign:
TextBox 0.00 txtWeek2Friday
Right
TextAlign:
TextBox 0.00 txtWeek2Saturday
Right
TextAlign:
TextBox 0.00 txtWeek2Sunday
Right
Label Notes
Multiline:
TextBox txtNotes
true
Button Submit btnSubmit
Button Close btnClose

3. Click the txtEmployeeNumber text box to select it


4. In the Properties window, click the Events button and generate the event of the Leave field
5. Return to the form and click the dtpStartDate DateTimePicker
6. In the Events section of the Properties window, generate the CloseUp event
7. Return to the form and double-click the Submit button
8. Return to the form and double-click the Close button
9. Change the file as follows:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace YNBTimeSheet2
{
public partial class Form1 : Form
{
bool ValidTimeSheet;
bool bNewRecord;
string strTimeSheetCode;

public Form1()
{
InitializeComponent();
}

private void txtEmployeeNumber_Leave(object sender, EventArgs e)


{
if( this.txtEmployeeNumber.Text == "" )
{
ValidTimeSheet = false;
return;
}

string strSelect =
string.Concat("SELECT * FROM Employees WHERE EmployeeNumber =
'",
this.txtEmployeeNumber.Text, "';");

SqlConnection conDatabase =
new SqlConnection("Data
Source=(local);Database='ynb1';" +
"Integrated Security=true");
SqlCommand cmdDatabase = new SqlCommand(strSelect, conDatabase);

DataSet dsEmployees = new DataSet();


SqlDataAdapter sda = new SqlDataAdapter();

sda.SelectCommand = cmdDatabase;
sda.Fill(dsEmployees);

try {
DataRow recEmployee = dsEmployees.Tables[0].Rows[0];

if( recEmployee.IsNull("EmployeeNumber") )
{
ValidTimeSheet = false;
throw new System.IndexOutOfRangeException("Bad Employee
Number!");
}
else
{
String strFullName =
(string)recEmployee["FirstName"] +
" " + (string)recEmployee["LastName"];
lblFullName.Text = "Welcome " +
strFullName;
ValidTimeSheet = true;

}
}
catch(IndexOutOfRangeException )
{
ValidTimeSheet = false;
lblFullName.Text = "";
MessageBox.Show("There is no employee with that number!");
txtEmployeeNumber.Text = "";
btnClose.Focus();
}

dtpStartDate.Value = DateTime.Today;

txtWeek1Monday.Text = "0.00";
txtWeek1Tuesday.Text = "0.00";
txtWeek1Wednesday.Text = "0.00";
txtWeek1Thursday.Text = "0.00";
txtWeek1Friday.Text = "0.00";
txtWeek1Saturday.Text = "0.00";
txtWeek1Sunday.Text = "0.00";

txtWeek2Monday.Text = "0.00";
txtWeek2Tuesday.Text = "0.00";
txtWeek2Wednesday.Text = "0.00";
txtWeek2Thursday.Text = "0.00";
txtWeek2Friday.Text = "0.00";
txtWeek2Saturday.Text = "0.00";
txtWeek2Sunday.Text = "0.00";

conDatabase.Close();
}

private void dtpStartDate_CloseUp(object sender, EventArgs e)


{
lblEndDate.Text = dtpStartDate.Value.AddDays(14).ToString();

if( txtEmployeeNumber.Text.Equals("") )
{
ValidTimeSheet = false;
return;
}

string strMonth;
string strDay;
int iMonth;
int iDay;
DateTime dteStart;

dteStart = dtpStartDate.Value;
iMonth = dteStart.Month;
iDay = dteStart.Day;

if( iMonth < 10 )


strMonth = dteStart.Year + "0" + iMonth.ToString();
else
strMonth = dteStart.Year + iMonth.ToString();

if( iDay < 10 )


strDay = strMonth + "0" + iDay.ToString();
else
strDay = strMonth + iDay.ToString();
strTimeSheetCode = txtEmployeeNumber.Text + strDay;
SqlConnection conTimeSheet = null;
string strSQL =
String.Concat("SELECT * FROM dbo.TimeSheets WHERE TimeSheetCode
= '",
strTimeSheetCode, "';");

conTimeSheet =
new SqlConnection("Data
Source=(local);Database='ynb1';" +
"Integrated Security=true");
SqlCommand cmdTimeSheet = new SqlCommand(strSQL, conTimeSheet);

DataSet dsTimeSheet = new DataSet("TimeSheetSet");


SqlDataAdapter sdaTimeSheet = new SqlDataAdapter();
sdaTimeSheet.SelectCommand = cmdTimeSheet;
sdaTimeSheet.Fill(dsTimeSheet);

conTimeSheet.Close();

try {
DataRow recTimeSheet = dsTimeSheet.Tables[0].Rows[0];
strTimeSheetCode = (string)(recTimeSheet["TimeSheetCode"]);

if( recTimeSheet.IsNull("TimeSheetCode") )
{
throw new System.IndexOutOfRangeException(
"No TimeSheet with that number exists!");
bNewRecord = true;
return;
}
else
{
txtWeek1Monday.Text = (string)(recTimeSheet["Week1Monday"]);
txtWeek1Tuesday.Text = (string)(recTimeSheet["Week1Tuesday"]);
txtWeek1Wednesday.Text = (string)
(recTimeSheet["Week1Wednesday"]);
txtWeek1Thursday.Text = (string)
(recTimeSheet["Week1Thursday"]);
txtWeek1Friday.Text = (string)(recTimeSheet["Week1Friday"]);
txtWeek1Saturday.Text = (string)
(recTimeSheet["Week1Saturday"]);
txtWeek1Sunday.Text = (string)(recTimeSheet["Week1Sunday"]);

txtWeek2Monday.Text = (string)(recTimeSheet["Week2Monday"]);
txtWeek2Tuesday.Text = (string)(recTimeSheet["Week2Tuesday"]);
txtWeek2Wednesday.Text = (string)
(recTimeSheet["Week2Wednesday"]);
txtWeek2Thursday.Text = (string)
(recTimeSheet["Week2Thursday"]);
txtWeek2Friday.Text = (string)(recTimeSheet["Week2Friday"]);
txtWeek2Saturday.Text = (string)
(recTimeSheet["Week2Saturday"]);
txtWeek2Sunday.Text = (string)(recTimeSheet["Week2Sunday"]);

bNewRecord = false;
}
}
catch(IndexOutOfRangeException )
{
txtWeek1Monday.Text = "0.00";
txtWeek1Tuesday.Text = "0.00";
txtWeek1Wednesday.Text = "0.00";
txtWeek1Thursday.Text = "0.00";
txtWeek1Friday.Text = "0.00";
txtWeek1Saturday.Text = "0.00";
txtWeek1Sunday.Text = "0.00";

txtWeek2Monday.Text = "0.00";
txtWeek2Tuesday.Text = "0.00";
txtWeek2Wednesday.Text = "0.00";
txtWeek2Thursday.Text = "0.00";
txtWeek2Friday.Text = "0.00";
txtWeek2Saturday.Text = "0.00";
txtWeek2Sunday.Text = "0.00";

bNewRecord = true;
}
}

private void btnTimeSheet_Click(object sender, EventArgs e)


{
string strTimeSheet = "";

// If this is new record, then create a new time sheet


if( bNewRecord == true )
{
strTimeSheet = String.Concat("INSERT INTO
dbo.TimeSheets(TimeSheetCode, ",
"EmployeeNumber, StartDate, Week1Monday,
Week1Tuesday, ",
"Week1Wednesday, Week1Thursday,
Week1Friday, Week1Saturday, Week1Sunday, ",
"Week2Monday, Week2Tuesday,
Week2Wednesday, Week2Thursday, Week2Friday, ",
"Week2Saturday, Week2Sunday, Notes) ",
"VALUES('", strTimeSheetCode, "', '",
txtEmployeeNumber.Text, "', '",

dtpStartDate.Value.ToString("MM/dd/yyyy"), "', '", txtWeek1Monday.Text,


"', '",
txtWeek1Tuesday.Text, "', '",
txtWeek1Wednesday.Text, "', '", txtWeek1Thursday.Text, "', '",
txtWeek1Friday.Text, "', '",
txtWeek1Saturday.Text, "', '",
txtWeek1Sunday.Text, "', '",
txtWeek2Monday.Text, "', '", txtWeek2Tuesday.Text, "', '",
txtWeek2Wednesday.Text, "', '",
txtWeek2Thursday.Text, "', '", txtWeek2Friday.Text, "', '",
txtWeek2Saturday.Text, "', '",
txtWeek2Sunday.Text, "', '", txtNotes.Text, "');");
}
// If this is an existing record, then, only update it
if( bNewRecord == false )
{
strTimeSheet = String.Concat("UPDATE TimeSheets SET Week1Monday
= '", txtWeek1Monday.Text,
"', Week1Tuesday = '",
txtWeek1Tuesday.Text, "', Week1Wednesday = '", txtWeek1Wednesday.Text,
"', Week1Thursday = '",
txtWeek1Thursday.Text, "', Week1Friday = '", txtWeek1Friday.Text,
"', Week1Saturday = '",
txtWeek1Saturday.Text, "', Week1Sunday = '", txtWeek1Sunday.Text,
"', Week2Monday = '",
txtWeek2Monday.Text, "', Week2Tuesday = '", txtWeek2Tuesday.Text,
"', Week2Wednesday = '",
txtWeek2Wednesday.Text, "', Week2Thursday = '", txtWeek2Thursday.Text,
"', Week2Friday = '",
txtWeek2Friday.Text, "', Week2Saturday = '", txtWeek2Saturday.Text,
"', Week2Sunday = '",
txtWeek2Sunday.Text, "', Notes = '", txtNotes.Text,
"' WHERE TimeSheetCode = '",
strTimeSheetCode, "';");
}

if( this.ValidTimeSheet == true )


{
SqlConnection conTimeSheet =
new SqlConnection("Data
Source=(local);Database='ynb1';" +
"Integrated Security=true");
SqlCommand cmdTimeSheet = new SqlCommand(strTimeSheet,
conTimeSheet);

conTimeSheet.Open();
cmdTimeSheet.ExecuteNonQuery();
conTimeSheet.Close();

MessageBox.Show("Your time sheet has been submitted");


}
else
{
MessageBox.Show("The time sheet is not valid\n" +
"either you didn't enter a valid employee
number, " +
"or you didn't a valid start date\n" +
"The time sheet will not be saved");
}
}

private void btnClose_Click(object sender, EventArgs e)


{
Close();
}
}
}
• Execute the application
Introduction
In this example, we will calculate the overtime worked by an employee of a
company. To do this, we will consider each week day with 8 regular hours. If an
employee works more than 8 hours in one day, any time over that is considered
overtime. In our payroll simulation, we will cover two weeks but each week has its
separate calculation. After collecting the time for both weeks and performing the
calculation, we will display the number of regular hours, the number of hours
worked overtime, the amount pay for the regular hours, and the amount pay for
overtime, if any. At the end, we will display the total net pay.

Practical Learning: Introducing the Date Picker


1. Start a new Windows Application named GCSPayroll1
2. Set the form's Icon to Drive:\Program Files\Microsoft Visual Studio .NET
2003\Common7\Graphics\icons\Office
\CRDFLE03.ICO
3. Design the form as follows:
Control Name Text Other Properties

GroupBox Employee Identification

Label Employee #:

TextBox txtEmployeeNbr

Label Hourly Salary:

TextBox txtHourlySalary

GroupBox Time Period

Label Starting Date:

DateTimePicker dtpStartingDate

Label End Date:

DateTimePicker dtpEndDate

GroupBox Time Sheet

Label Monday

Label Tuesday

Label Wednesday

Label Thursday

Label Friday

Label Saturday

Label Sunday

Label First Week:

TextBox txtMonday1 0.00 TextAlign: Right

TextBox txtTuesday1 0.00 TextAlign: Right

TextBox txtWednesday1 0.00 TextAlign: Right

TextBox txtThursday1 0.00 TextAlign: Right

TextBox txtFriday1 0.00 TextAlign: Right


TextBox txtSaturday1 0.00 TextAlign: Right

TextBox txtSunday1 0.00 TextAlign: Right

Label Second Week:

TextBox txtMonday2 0.00 TextAlign: Right

TextBox txtTuesday2 0.00 TextAlign: Right

TextBox txtWednesday2 0.00 TextAlign: Right

TextBox txtThursday2 0.00 TextAlign: Right

TextBox txtFriday2 0.00 TextAlign: Right

TextBox txtSaturday2 0.00 TextAlign: Right

TextBox txtSunday2 0.00 TextAlign: Right

GroupBox Payroll Processing

Label Hours

Label Amount

Button btnProcessIt Process It

Label Regular

TextBox txtRegularHours 0.00 TextAlign: Right

TextBox txtRegularAmount 0.00 TextAlign: Right

Label Total Earnings

TextBox txtTotalEarnings 0.00 TextAlign: Right

Label Overtime

TextBox txtOvertimeHours 0.00 TextAlign: Right

TextBox txtOvertiimeAmount 0.00 TextAlign: Right

Button btnClose

4. Double-click the Close button and implement its Click event as follows:

private void btnClose_Click(object sender, System.EventArgs e)


{
Close();
}
5. Execute it to test it and then close the form
6. Double-click an unoccupied area of the form and implement its Load event as
follows:

private void Form1_Load(object sender, System.EventArgs e)


{
DateTime todayDate = DateTime.Today;
DateTime twoWeeksAgo = todayDate.AddDays(-14);

this.dtpStartingDate.Value = twoWeeksAgo;
}
7. Return to the form and click the top DateTimePicker control

8. In the Properties window, click the Events button and double-click the
CloseUp field
9. Implement the event as follows:

private void dtpStartingDate_CloseUp(object sender, System.EventArgs


e)
{
// Get the starting date
DateTime dteStart = this.dtpStartingDate.Value;

// Find out if the user selected a day that is not Monday


if( dteStart.DayOfWeek != DayOfWeek.Monday )
{
MessageBox.Show("The date you selected in invalid\n" +
"The time period should start on a Monday");

this.dtpStartingDate.Focus();
}
}
10. Return to the form and click the other DateTimePicker control

11. In the Properties window, click the Events button and double-click the
CloseUp field
12. Implement the event as follows:

private void dtpEndDate_CloseUp(object sender, System.EventArgs e)


{
// Get the starting date
DateTime dteStart = this.dtpStartingDate.Value;
// Get the ending date
DateTime dteEnd = this.dtpEndDate.Value;

// Make sure the first day of the period is Monday


if( dteStart.DayOfWeek != DayOfWeek.Monday )
{
MessageBox.Show("The starting date you selected in invalid\n"
+
"The time period should start on a Monday");

this.dtpStartingDate.Focus();
}

// Find the number of days that separate the start and end
TimeSpan timeDifference = dteEnd.Subtract(dteStart);
double fourteenDaysLater = timeDifference.Days;

if( (dteEnd.DayOfWeek != DayOfWeek.Sunday) || (fourteenDaysLater !=


13) )
{
MessageBox.Show("The ending date you selected in invalid\n" +
"The time period should span 2 weeks and end on a
Sunday");

this.dtpEndDate.Focus();
}
}
13. Return to the form. Double-click the Process It button and implement its Click
event as follows:

private void btnPresseIt_Click(object sender, System.EventArgs e)


{
double monday1 = 0.00, tuesday1 = 0.00, wednesday1 = 0.00, thursday1 =
0.00,
friday1 = 0.00, saturday1 = 0.00, sunday1 = 0.00,
monday2 = 0.00, tuesday2 = 0.00, wednesday2 = 0.00, thursday2
= 0.00,
friday2 = 0.00, saturday2 = 0.00, sunday2 = 0.00;
double totalHoursWeek1, totalHoursWeek2;

double regHours1 = 0.00, regHours2 = 0.00, ovtHours1 = 0.00, ovtHours2


= 0.00;
double regAmount1 = 0.00, regAmount2 = 0.00, ovtAmount1 = 0.00,
ovtAmount2 = 0.00;
double regularHours, overtimeHours;
double regularAmount, overtimeAmount, totalEarnings;

double hourlySalary = 0.00;

// Retrieve the hourly salary


try
{
hourlySalary = double.Parse(this.txtHourlySalary.Text);
}
catch(FormatException)
{
MessageBox.Show("The value you typed for the salary is
invalid \n" +
"Please try again");
this.txtHourlySalary.Focus();
}

// Retrieve the value of each day worked


try
{
monday1 = double.Parse(this.txtMonday1.Text);
}
catch(FormatException)
{
MessageBox.Show("You typed an invalid value\n" +
"Please try again");
this.txtMonday1.Focus();
}
try
{
tuesday1 = double.Parse(this.txtTuesday1.Text);
}
catch(FormatException)
{
MessageBox.Show("You typed an invalid value\n" +
"Please try again");
this.txtTuesday1.Focus();
}
try
{
wednesday1 = double.Parse(this.txtWednesday1.Text);
}
catch(FormatException)
{
MessageBox.Show("You typed an invalid value\n" +
"Please try again");
this.txtWednesday1.Focus();
}
try
{
thursday1 = double.Parse(this.txtThursday1.Text);

}
catch(FormatException)
{
MessageBox.Show("You typed an invalid value\n" +
"Please try again");
this.txtThursday1.Focus();
}
try
{
friday1 = double.Parse(this.txtFriday1.Text);
}
catch(FormatException)
{
MessageBox.Show("You typed an invalid value\n" +
"Please try again");
this.txtFriday1.Focus();
}
try
{
saturday1 = double.Parse(this.txtSaturday1.Text);
}
catch(FormatException)
{
MessageBox.Show("You typed an invalid value\n" +
"Please try again");
this.txtSaturday1.Focus();
}
try
{
sunday1 = double.Parse(this.txtSunday1.Text);
}
catch(FormatException)
{
MessageBox.Show("You typed an invalid value\n" +
"Please try again");
this.txtSunday1.Focus();
}
try
{
monday2 = double.Parse(this.txtMonday2.Text);
}
catch(FormatException)
{
MessageBox.Show("You typed an invalid value\n" +
"Please try again");
this.txtMonday2.Focus();
}
try
{
tuesday2 = double.Parse(this.txtTuesday2.Text);
}
catch(FormatException)
{
MessageBox.Show("You typed an invalid value\n" +
"Please try again");
this.txtTuesday2.Focus();
}
try
{
wednesday2 = double.Parse(this.txtWednesday2.Text);
}
catch(FormatException)
{
MessageBox.Show("You typed an invalid value\n" +
"Please try again");
this.txtWednesday2.Focus();
}
try
{
thursday2 = double.Parse(this.txtThursday2.Text);
}
catch(FormatException)
{
MessageBox.Show("You typed an invalid value\n" +
"Please try again");
this.txtThursday2.Focus();
}
try
{
friday2 = double.Parse(this.txtFriday2.Text);
}
catch(FormatException)
{
MessageBox.Show("You typed an invalid value\n" +
"Please try again");
this.txtFriday2.Focus();
}
try
{
saturday2 = double.Parse(this.txtSaturday2.Text);
}
catch(FormatException)
{
MessageBox.Show("You typed an invalid value\n" +
"Please try again");
this.txtSaturday2.Focus();
}
try
{
sunday2 = double.Parse(this.txtSunday2.Text);
}
catch(FormatException)
{
MessageBox.Show("You typed an invalid value\n" +
"Please try again");
this.txtSunday2.Focus();
}

// Calculate the total number of hours for each week


totalHoursWeek1 = monday1 + tuesday1 + wednesday1 + thursday1 +
friday1 + saturday1 + sunday1;
totalHoursWeek2 = monday2 + tuesday2 + wednesday2 + thursday2 +
friday2 + saturday2 + sunday2;

// The overtime is paid time and half


double ovtSalary = hourlySalary * 1.5;

// If the employee worked under 40 hours, there is no overtime


if( totalHoursWeek1 < 40 )
{
regHours1 = totalHoursWeek1;
regAmount1 = hourlySalary * regHours1;
ovtHours1 = 0.00;
ovtAmount1 = 0.00;
} // If the employee worked over 40 hours, calculate the overtime
else if( totalHoursWeek1 >= 40 )
{
regHours1 = 40;
regAmount1 = hourlySalary * 40;
ovtHours1 = totalHoursWeek1 - 40;
ovtAmount1 = ovtHours1 * ovtSalary;
}

if( totalHoursWeek2 < 40 )


{
regHours2 = totalHoursWeek2;
regAmount2 = hourlySalary * regHours2;
ovtHours2 = 0.00;
ovtAmount2 = 0.00;
}
else if( totalHoursWeek2 >= 40 )
{
regHours2 = 40;
regAmount2 = hourlySalary * 40;
ovtHours2 = totalHoursWeek2 - 40;
ovtAmount2 = ovtHours2 * ovtSalary;
}

regularHours = regHours1 + regHours2;


overtimeHours = ovtHours1 + ovtHours2;
regularAmount = regAmount1 + regAmount2;
overtimeAmount = ovtAmount1 + ovtAmount2;
totalEarnings = regularAmount + overtimeAmount;

this.txtRegularHours.Text = regularHours.ToString("F");
this.txtOvertimeHours.Text = overtimeHours.ToString("F");
this.txtRegularAmount.Text = regularAmount.ToString("F");
this.txtOvertimeAmount.Text = overtimeAmount.ToString("F");

this.txtTotalEarnings.Text = totalEarnings.ToString("F");
}
14. Execute the application to test it

15. After using it, close the form and return to your programming environment

Georgetown Cleaning Services


Command Buttons
This exercise is meant to apply the concepts of a Button control. It is used to process simple
orders for a cleaning store.

Practical Learning: Introducing Buttons


1. Start a new Windows Application named GCS1
2. Set the form's icon to Drive:\Program Files\Microsoft Visual Studio .NET
2003\Common7\Graphics\icons\Misc\BULLSEYE.ICO
3. Design the form as follows:
Control Name Text Additional Properties

GroupBox Order Setup

Label Customer Name:

TextBox txtCustName

Label Order Date:

Format: dddd dd mmmm yyyy


MaskedEdBox txtOrderDate
Mask: ##-##-##

Label Order Time:

Format: hh:mm AM/PM


MaskedEdBox txtOrderTime
Mask: ##:##

GroupBox Order Processing

Label Item Type

Label Qty

Label Unit Price

Label Sub Total

Label Shirts

TextBox txtQtyShirts 0 TextAlign: Right

TextBox txtPriceShirts 0.95 TextAlign: Right


TextAlign: Right
TextBox txtTotalShirts 0.00
ReadOnly: True

Label Pants

TextBox txtQtyPants 0 TextAlign: Right

TextBox txtPricePants 2.95 TextAlign: Right

TextAlign: Right
TextBox txtTotalPants 0.00
ReadOnly: True

Label Dresses

TextBox txtQtyDresses 0 TextAlign: Right

TextBox txtPriceDresses 2.95 TextAlign: Right

TextAlign: Right
TextBox txtTotaldresses 4.55
ReadOnly: True

Button btnCalculate Calculate

GroupBox Order Summary

Label Total Order

TextAlign: Right
TextBox txtTotalOrder 0.00
ReadOnly: True

Label TaxRate

TextBox txtTaxRate 5.75 TextAlign: Right

Label %

Label Tax Amount

TextAlign: Right
TextBox txtTaxAmount 0.00
ReadOnly: True

Label Net Price

TextAlign: Right
TextBox txtNetPrice 0.00
ReadOnly: True

Button btnClose Close

4. Save All
5. On the main menu, click File -> New -> File...
6. In the New File dialog box, double-click Icon File
7. Right-click a white area in the drawing section, position the mouse on Current Icon Image Types,
Colors
8. Save it as Calculate in the main folder of the current project
9. Change its design as follows:

10. Right-click a white area in the drawing section, position the mouse on Current Icon Image Types,
Colors
11. Right-click a white area in the drawing section and click Delete Image Type
12. Save the icon
13. On the main menu, click Project -> Add New Item...
14. In the Add New Item dialog box, click Icon File
15. Change the name to SubTotal and click Open
16. Right-click a white area in the drawing section, position the mouse on Current Icon Image Types,
Colors
17. Change its design as follows:

18. Right-click a white area in the drawing section, position the mouse on Current Icon Image Types,
Colors
19. Right-click a white area in the drawing section and click Delete Image Type
20. Save the icon
21. Add three buttons inside the lower-left group box and delete the content of their Text property
22. Complete the design of the form as follows:
Button Name Image ImageAlign TextAlign
btnShirts SubTotal
btnPants SubTotal
btnDresses SubTotal
btnCalculate Calculate TopCenter BottomCenter

23. On the main menu, click View Tab Order and click the controls in the following order (observe the
Order Processing group box)

24. Save all


25. Double-click the button for the shirts and implement its Click event as follows:
private void btnShirts_Click(object sender, System.EventArgs e)
{
int quantity = 1;
double unitPrice = 0.00, subTotal;

// Retrieve the number of this item


// Just in case the user types an invalid value, we are using a
try...catch
try
{
quantity = int.Parse(this->txtQtyShirts->Text);
}
catch(FormatException)
{
MessageBox::Show("The value you entered for the number of shirts
is not valid" +
"\nPlease try again");
}

// Retrieve the unit price of this item


// Just in case the user types an invalid value, we are using a
try...catch
try
{
unitPrice = double.Parse(this->txtPriceShirts->Text);
}
catch(FormatException)
{
MessageBox::Show("The value you entered for the price of shirts is
not valid" +
"\nPlease try again");
}

// Calculate the sub-total for this item


subTotal = quantity * unitPrice;

// Display the sub-total in the corresponding text box


this->txtTotalShirts->Text = subTotal.ToString("F");
}
26. Double-click the button for the pants and implement its Click event as follows:

private void btnPants_Click(object sender, System.EventArgs e)


{
int quantity = 1;
double unitPrice = 0.00, subTotal;

try
{
quantity = int.Parse(this->txtQtyPants->Text);
}
catch(FormatException)
{
MessageBox::Show("The value you entered for the number of pants is
not valid" +
"\nPlease try again");
}

try
{
unitPrice = double.Parse(this->txtPricePants->Text);
}
catch(FormatException)
{
MessageBox::Show("The value you entered for the price of pants is
not valid" +
"\nPlease try again");
}

subTotal = quantity * unitPrice;

this->txtTotalPants->Text = subTotal.ToString("F");
}
27. Double-click the button for the dresses and implement its Click event as follows:

private void btnDresses_Click(object sender, System.EventArgs e)


{
int quantity = 1;
double unitPrice = 0.00, subTotal;

try
{
quantity = int.Parse(this->txtQtyDresses->Text);
}
catch(FormatException)
{
MessageBox::Show("The value you entered for the number of dresses
not valid" +
"\nPlease try again");
}

try
{
unitPrice = double.Parse(this->txtPriceDresses->Text);
}
catch(FormatException)
{
MessageBox::Show("The value you entered for the price of dresses i
not valid" +
"\nPlease try again");
}

subTotal = quantity * unitPrice;

this->txtTotalDresses->Text = subTotal.ToString("F");
}
28. Double-click the Calculate button and implement its Click event as follows:
private void btnCalculate_Click(object sender, System.EventArgs e)
{
double priceShirts, pricePants, priceDresses, totalOrder;
double taxRate = 0.00, taxAmount;
double netPrice;

// Retrieve the value of the sub-total for each category of


items
priceShirts = double.Parse(this->txtTotalShirts->Text);
pricePants = double.Parse(this->txtTotalPants->Text);
priceDresses = double.Parse(this->txtTotalDresses->Text);

// Calculate the total


totalOrder = priceShirts + pricePants + priceDresses;

// Retrieve the value of the tax rate


try
{
taxRate = double.Parse(this->txtTaxRate->Text);
}
catch(FormatException)
{
MessageBox::Show("The tax rate you entered is invalid"
+
"\nPlease try again");
}

// Calculate the amount owed for the taxes


taxAmount = totalOrder * taxRate / 100;
// Add the tax amount to the total order
netPrice = totalOrder + taxAmount;

// Display the values of the order summary


this->txtTotalOrder->Text = totalOrder.ToString("C");
this->txtTaxAmount->Text = taxAmount.ToString("C");
this->txtNetPrice->Text = netPrice.ToString("C");
}
29. Double-click the Close button and implement its Click event as follows:

private void btnClose_Click(object sender, System.EventArgs e)


{
Close();
}

30. Execute the application to test the form. In the Order Date text box, type 081103 and in the Ord
then complete the rest of the order
31. Close the form and return to your programming environment

Multiple-Choice Question: Single Answer


Introduction
A multiple choice program is an application that displays a question and a few possible answers
in a continuous manner. This application is also called a multiple-choice question or MCQ. After
reading the question, the user consults the available answers and selects the one or those that
constitute the right answer. After answering a question, the user is provided with a means of
moving to the next question. In most cases, the user can also move to the previous question. In
some applications, the user can stop the test or application anytime by closing it or by using a
control.

When the application starts, you can display the first question to the user. In some cases, before
displaying the questions to the user, you can provide a way to specify the desired number of
questions.

Practical Learning: Creating a Multiple-Choice Test


1. Start Microsoft Visual C# and create a Windows Application named DrivingTest1
2. Design the form as follows:
Additional
Control Text Name
Properties
Label Number of Questions:
Maximum: 20
NumericUpDown updTotalQuestions
Value: 5
Button Start btnStart
Button Close btnClose

3. Save all

Single-Answer Questions
The most basic MCQ application displays a question and two to four possible answers for a single
choice. The top section of a window displays a question. Under the question, two to four radio
buttons display the possible answers. The user can then click one of them. After making a
choice, the user can click a button to advance to the next question.

Practical Learning: Creating the Questions


1. To add a new form, on the main menu, click Project -> Add Windows Form...
2. In the Add New Item dialog box, set the Name QuestionAnswer
3. Click Add
4. Design the form as follows:
Control Caption Name Additional Properties
Label Question lblQuestion
Multiline: True
TextBox txtQuestion
ScrollBars: Vertical
Group Box Answer
AutoSize: False
Radio Button rdoAnswer1 CheckAlign: TopLeft
TextAlign: TopLeft
AutoSize: False
CheckAlign:
Radio Button rdoAnswer2
TopLeft
TextAlign: TopLeft
AutoSize: False
CheckAlign:
Radio Button rdoAnswer3
TopLeft
TextAlign: TopLeft
AutoSize: False
CheckAlign:
Radio Button rdoAnswer4
TopLeft
TextAlign: TopLeft
Button Quit btnQuit
Button Check Answer btnCheckAnswer
ShowInTaskbar:
Form
false

5. Save All
6. On the form, double-click the Quit button
7. Make the following changes:

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace DrivingTest1a
{
public partial class QuestionAnswer : Form
{
public int TotalNumberOfQuestions;

// This variable will hold a list of randoom non-repeating


numbers
ArrayList lstNumbers;
// This will represent the index of the question that is
being asked
int CurrentQuestion;
// These will keep a count of the questions already asked
int QuestionCounter;
int CurrentNumberOfQuestions;
// This will be used to counte the number of correct answers
double Sum;
const int MaximumNumberOfQuestions = 20;
// This variable allows monitoring if a 0 had been
// added to the list of numbers;
bool Found0;

public QuestionAnswer()
{
InitializeComponent();
}

// This method takes a constant integer that represents


// the index of a question in the list of questions
// This method then displays the corresponding question
void PresentQuestion(int qstNumber)
{
rdoAnswer1.Checked = false;
rdoAnswer2.Checked = false;
rdoAnswer3.Checked = false;
rdoAnswer4.Checked = false;
switch (qstNumber)
{
case 1:
txtQuestion.Text = "If your car and a car coming
from your " +
"right reach an intersection
at the same " +
"time, who has the right of
way?";

rdoAnswer1.Text = "A. Your car";


rdoAnswer2.Text = "B. The other car";
rdoAnswer3.Text = "C. You both wait for the first
car that makes a move";
rdoAnswer4.Text = "D. Neither, as both cars must
come to a stop";
break;

case 2:
txtQuestion.Text = "How many feet before you make
a turn should " +
"you signal that you are going
to turn?";

rdoAnswer1.Text = "A. 50 feet";


rdoAnswer2.Text = "B. 100 feet";
rdoAnswer3.Text = "C. 150 feet";
rdoAnswer4.Text = "D. While turning";

break;

case 3:
txtQuestion.Text = "You are driving in an alley
at fifteen (15) " +
"miles per hour. You are";

rdoAnswer1.Text = "A. Breaking the speed limit


for alleys";
rdoAnswer2.Text = "B. Driving too slow";
rdoAnswer3.Text = "C. Obeying the law";
rdoAnswer4.Text = "D. Breaking the law as you
should never drive " +
"in an alley";
break;

case 4:
txtQuestion.Text = "A car driving toward you " +
"at night and it has its
blinding " +
"high beam lights on. The
driver of this car is";

rdoAnswer1.Text = "A. Guilty only of bad manners


because the " +
"high beams blind other
drivers";
rdoAnswer2.Text = "B. A safe driver because the
high beams " +
"light up the road more
brightly than " +
"the lower beams";
rdoAnswer3.Text = "C. Not obeying the law because
the low beams " +
"must be used at all times";
rdoAnswer4.Text = "D. not doing anything wrong
(it doesn't matter";
break;

case 5:
txtQuestion.Text = "You are driving up to an
intersection where " +
"there is no signal light or
policeman. A man " +
"is crossing in the cross walk
in front of " +
"your car. You should:";

rdoAnswer1.Text = "A. Continue into the


intersection because you " +
"have the right-of-way";
rdoAnswer2.Text = "B. Slow down and be careful";
rdoAnswer3.Text = "C. Stop and give him the
right-of way";
rdoAnswer4.Text = "D. Not care";
break;

case 6:
txtQuestion.Text = "You wish to make a \"U\" turn
at an intersection " +
"controlled by a traffic light.
You should: ";

rdoAnswer1.Text = "A. Drive to another


intersection that has no traffic " +
"light or sign saying NO \"U\"
Turn";
rdoAnswer2.Text = "B. Wait until the light turns
green before making " +
"the \"U\" turn";
rdoAnswer3.Text = "C. Make the \"U\" turn if
there is a policeman " +
"at the intersection";
rdoAnswer4.Text = "D. Wait for the red light
before making the \"U\" " +
"turn to make sure that the
opposing traffic is safe";
break;

case 7:
txtQuestion.Text = "You are driving past a school
building or its " +
"grounds when the children are
going to or " +
"leaving school. The speed
limit is:";

rdoAnswer1.Text = "A. Seven (7) miles per hour";


rdoAnswer2.Text = "B. Fifteen (15) miles per
hour";
rdoAnswer3.Text = "C. Ten (10) miles per hour";
rdoAnswer4.Text = "D. Twenty (20) miles per
hour";
break;

case 8:
txtQuestion.Text = "If you are driving out of an
alley " +
"or driveway, you must";

rdoAnswer1.Text = "A. Stop before reaching the


sidewalk";
rdoAnswer2.Text = "B. Stop, if possible to do so
safely";
rdoAnswer3.Text = "C. Stop only if there is heavy
traffic";
rdoAnswer4.Text = "D. Wait for a policeman of
respectable " +
"pedestrian to guide you when
it is safer";
break;

case 9:
txtQuestion.Text = "You are coming to an
intersection " +
"where there is a flashing
yellow traffic " +
"light. You should";

rdoAnswer1.Text = "A. Slow down and proceed with


caution";
rdoAnswer2.Text = "B. Stop, if possible to do so
safely";
rdoAnswer3.Text = "C. Continue at the same
speed";
rdoAnswer4.Text = "D. Wait for a poileman to
direct the traffic";
break;

case 10:
txtQuestion.Text = "You are driving on a two-lane
street. " +
"The car ahead of you is
moving very slowly " +
"and the road ahead is clear
for passing. " +
"You should:";
rdoAnswer1.Text = "A. Pass on the left hand
side";
rdoAnswer2.Text = "B. Pass on either side";
rdoAnswer3.Text = "C. Pass on the right side";
rdoAnswer4.Text = "D. Make a gesture to signal
the other car " +
"to move to the other lane, so
you can " +
"drive straight";
break;

case 11:
txtQuestion.Text = "What is the legal rate of
speed " +
"unless there are signs " +
"that give a different speed
limit?";

rdoAnswer1.Text = "A. 25 miles per hour";


rdoAnswer2.Text = "B. 30 miles per hour";
rdoAnswer3.Text = "C. 35 miles per hour";
rdoAnswer4.Text = "D. 45 miles per hour";
break;

case 12:
txtQuestion.Text = "You are driving a car which
is involved in " +
"an accident. Two people are
slightly hurt " +
"but don't need to go to the
hospital. " +
"You should:";

rdoAnswer1.Text = "A. Report to the nearest


police pricinct";
rdoAnswer2.Text = "B. Report to the Department of
Motor Vehicles";
rdoAnswer3.Text = "C. Report to the police and
the Department of " +
"Motor Vehicles";
rdoAnswer4.Text = "D. Wait for a policeman";
break;

case 13:
txtQuestion.Text = "You're driving up to an
intersection where " +
"the traffic light is red. A
policeman " +
"motions you to go through.
You should";

rdoAnswer1.Text = "A. Wait for the light to turn


green and " +
"then go ahead";
rdoAnswer2.Text = "B. Call the policeman's
attention to " +
"the red light";
rdoAnswer3.Text = "C. Obey the policeman's
signal";
rdoAnswer4.Text = "D. Wait for another car to
move to make " +
"sure the road is safe";
break;

case 14:
txtQuestion.Text = "You are pulling into the
street from a " +
"parallel parking space.
Before doing " +
"so, you should:";

rdoAnswer1.Text = "A. Blow your horn and pull


from the curb slowly";
rdoAnswer2.Text = "B. Signal other traffic and
then pull into the street";
rdoAnswer3.Text = "C. Proceed with caution when
there is no traffic " +
"near enough to cause an
accident";
rdoAnswer4.Text = "D. Wait for a policeman or a
respectable citizen " +
"to signal that the road is
safer";
break;

case 15:
txtQuestion.Text = "You have changed your
address. You should notify " +
"the Department of Motor
Vehicles, either by " +
"mail or in person, within a
period of:";

rdoAnswer1.Text = "A. Fifteen (15) days";


rdoAnswer2.Text = "B. Five (5) days";
rdoAnswer3.Text = "C. Thirty (30) days";
rdoAnswer4.Text = "D. Ten (10) days";
break;

case 16:
txtQuestion.Text = "You are driving on a street
and another car is " +
"entering the street from a
driveway. Who has " +
"the right-of-way?";

rdoAnswer1.Text = "A. You";


rdoAnswer2.Text = "B. The other driver";
rdoAnswer3.Text = "C. Neither you nor the other
driver";
rdoAnswer4.Text = "D. The next car";
break;
case 17:
txtQuestion.Text = "Up to what age are children
required to " +
"be restrained in a child
restraint seat?";

rdoAnswer1.Text = "A. 6 months old";


rdoAnswer2.Text = "B. 3 years";
rdoAnswer3.Text = "C. 6 years";
rdoAnswer4.Text = "D. 8 years";
break;

case 18:
txtQuestion.Text = "How close to a fire hydrant
(fire plug) " +
"may you park a motor
vehicle?";

rdoAnswer1.Text = "A. Five (5) feet";


rdoAnswer2.Text = "B. Six (6) feet";
rdoAnswer3.Text = "C. Ten (10) feet";
rdoAnswer4.Text = "D. It doesn't matter because
you will " +
"move your car if the fire
fighters request it";
break;

case 19:
txtQuestion.Text = "When the light is green and
the yellow " +
"light comes on as you
approach an " +
"intersection, you should";

rdoAnswer1.Text = "A. Hurry to cross";


rdoAnswer2.Text = "B. Stop the crosswalk";
rdoAnswer3.Text = "C. Proceed accross the
intersection with caution";
rdoAnswer4.Text = "D. Before deciding about what
to do, check if the " +
"intersection is equipped with
cameras";
break;

case 20:
txtQuestion.Text = "A flashing red traffic light
signals means the same as:";

rdoAnswer1.Text = "A. Stop sign";


rdoAnswer2.Text = "B. Yield right-of-way sign";
rdoAnswer3.Text = "C. Slow sign";
rdoAnswer4.Text = "D. An ambulance is
approaching";
break;
case 21:
txtQuestion.Text = "How close to the intersection
are you allowed " +
"to park on a two-way
street?";

rdoAnswer1.Text = "A. Twenty (20) feet";


rdoAnswer2.Text = "B. Thirt (30) feet";
rdoAnswer3.Text = "C. Fourty (40) feet";
rdoAnswer4.Text = "D. Fifty (50) feet";
break;
}
}

private void btnQuit_Click(object sender, EventArgs e)


{
double average = 1;

if (QuestionCounter != 0)
average = Sum / QuestionCounter;
string strCongratulations = "";

if (average >= 0.5)


strCongratulations = "\nCongratulations!";

if (Found0 == true )
QuestionCounter--;

MessageBox.Show("Total Number of Questions: " +


QuestionCounter.ToString() +
"\nNumber of Correct Answers: " +
Sum.ToString() +
"\nSuccess Rate: " +
(average * 100).ToString("F") +
" %\n" + strCongratulations);
lstNumbers.Remove(MaximumNumberOfQuestions);
Close();
}
}
}
8. Under the Click event of the Quit button, implement the following method:

// This method takes as argument a constant integer


// The argument represents a question that was
// previously asked. The method checks the indexed
// question against its valid answer. If the answer
// to the question is valid, a total value is increased
void CheckAnswer(int qstNumber)
{
switch (qstNumber)
{
case 1:
if (rdoAnswer2.Checked == true)
{
MessageBox.Show("Correct");
Sum++;
}
else
MessageBox.Show("Wrong Answer");
break;

case 2:
if (rdoAnswer2.Checked == true)
{
MessageBox.Show("Correct");
Sum++;
}
else
MessageBox.Show("Wrong Answer");
break;

case 3:
if (rdoAnswer3.Checked == true)
{
MessageBox.Show("Correct");
Sum++;
}
else
MessageBox.Show("Wrong Answer");
break;

case 4:
if (rdoAnswer3.Checked == true)
{
MessageBox.Show("Correct");
Sum++;
}
else
MessageBox.Show("Wrong Answer");
break;

case 5:
if (rdoAnswer3.Checked == true)
{
MessageBox.Show("Correct");
Sum++;
}
else
MessageBox.Show("Wrong Answer");
break;

case 6:
if (rdoAnswer1.Checked == true)
{
MessageBox.Show("Correct");
Sum++;
}
else
MessageBox.Show("Wrong Answer");
break;
case 7:
if (rdoAnswer2.Checked == true)
{
MessageBox.Show("Correct");
Sum++;
}
else
MessageBox.Show("Wrong Answer");
break;

case 8:
if (rdoAnswer1.Checked == true)
{
MessageBox.Show("Correct");
Sum++;
}
else
MessageBox.Show("Wrong Answer");
break;

case 9:
if (rdoAnswer1.Checked == true)
{
MessageBox.Show("Correct");
Sum++;
}
else
MessageBox.Show("Wrong Answer");
break;

case 10:
if (rdoAnswer1.Checked == true)
{
MessageBox.Show("Correct");
Sum++;
}
else
MessageBox.Show("Wrong Answer");
break;

case 11:
if (rdoAnswer1.Checked == true)
{
MessageBox.Show("Correct");
Sum++;
}
else
MessageBox.Show("Wrong Answer");
break;

case 12:
if (rdoAnswer3.Checked == true)
{
MessageBox.Show("Correct");
Sum++;
}
else
MessageBox.Show("Wrong Answer");
break;

case 13:
if (rdoAnswer3.Checked == true)
{
MessageBox.Show("Correct");
Sum++;
}
else
MessageBox.Show("Wrong Answer");
break;

case 14:
if (rdoAnswer3.Checked == true)
{
MessageBox.Show("Correct");
Sum++;
}
else
MessageBox.Show("Wrong Answer");
break;

case 15:
if (rdoAnswer2.Checked == true)
{
MessageBox.Show("Correct");
Sum++;
}
else
MessageBox.Show("Wrong Answer");
break;

case 16:
if (rdoAnswer1.Checked == true)
{
MessageBox.Show("Correct");
Sum++;
}
else
MessageBox.Show("Wrong Answer");
break;

case 17:
if (rdoAnswer2.Checked == true)
{
MessageBox.Show("Correct");
Sum++;
}
else
MessageBox.Show("Wrong Answer");
break;

case 18:
if (rdoAnswer3.Checked == true)
{
MessageBox.Show("Correct");
Sum++;
}
else
MessageBox.Show("Wrong Answer");
break;

case 19:
if (rdoAnswer2.Checked == true)
{
MessageBox.Show("Correct");
Sum++;
}
else
MessageBox.Show("Wrong Answer");
break;

case 20:
if (rdoAnswer1.Checked == true)
{
MessageBox.Show("Correct");
Sum++;
}
else
MessageBox.Show("Wrong Answer");
break;

case 21:
if (rdoAnswer3.Checked == true)
{
MessageBox.Show("Correct");
Sum++;
}
else
MessageBox.Show("Wrong Answer");
break;
}

if (CurrentNumberOfQuestions == (TotalNumberOfQuestions +
1))
{
btnQuit_Click(null, null);
}
}
9. Return to the form
10. Double-click the Check Answer button and implement its event as follows:

private void btnCheckAnswer_Click(object sender, EventArgs e)


{
CurrentNumberOfQuestions++;
CheckAnswer(CurrentQuestion);

if (QuestionCounter >= lstNumbers.Count)


return;
CurrentQuestion = (int)(lstNumbers[QuestionCounter++]);

if (CurrentQuestion == 0)
{
Found0 = true;
CurrentQuestion = (int)(lstNumbers[QuestionCounter+
+]);
}

PresentQuestion(CurrentQuestion);
}
11. Return to the form and double-click an unoccupied area of its body
12. Implement the event as follows:

private void QuestionAnswer_Load(object sender, EventArgs e)


{
Found0 = false;
QuestionCounter = 0;

CurrentNumberOfQuestions = 0;

lstNumbers = new ArrayList();


Random rndNumber = new Random();

int number = rndNumber.Next(1, MaximumNumberOfQuestions + 1);


lstNumbers.Add(number);
int count = 0;

// Create a list of 20 non-repeating integers randomly chosen


do
{
// Randomly choose between 1 and the MaximumNumberOfQuestions
number = rndNumber.Next(0, MaximumNumberOfQuestions + 1);

// If the chosen number is not yet in the list,


// then add it
if (!lstNumbers.Contains(number))
{
lstNumbers.Add(number);
}// If the number is already in the list, ignore it

count++;
} while (count <= 100);

btnCheckAnswer_Click(sender, e);
}
13. Display the first form
14. Double-click the Start button and implement its event as follows:

private void btnStart_Click(object sender, EventArgs e)


{
QuestionAnswer frmAnswer = new QuestionAnswer();
int numberOfQuestions =
int.Parse(updTotalQuestions.Value.ToString());

frmAnswer.TotalNumberOfQuestions = numberOfQuestions;
frmAnswer.ShowDialog();
}
15. Display the first form again
16. Double-click the Close button and implement its event as follows:

private void btnClose_Click(object sender, EventArgs e)


{
Close();
}
17. Execute the application to see the result

Multiple-Choice Question: Multiple


Answers
Introduction
A multiple-choice exercise usually consists of single answers. This can done using radio buttons.
Another type of multiple-choice application can be made of single and multiple answers. In such
a program, the user can be presented with two types of questions, some requiring one answer
out of many options, and some others allowing the user to select more than one answer. When
creating the application, you must find a way to alternate the questions. Furthermore, you may
want to randomly present the questions. There are different ways you can do this.

Practical Learning: Creating a Multiple-Choice Test


1. Start Microsoft Visual C# and create a Windows Application named CSharpKnowledge1
2. Design the form as follows:

Additional
Control Text Name
Properties
Label Number of Questions:
Maximum: 20
NumericUpDown nudQuestions
Value: 5
Button Start btnStart
Button Close btnClose

3. Save all

Single and Multi-Answer Questions


If you want to create a multiple-choice application, you must find a way to alternate questions.
There are various ways you can do this. You can create a series of radio buttons and check
boxes. Then, when asking a question that expects a single answer, you can present only the
radio buttons. When a question expects more than one answer, you can present the check
boxes. Because of the way controls are built, you can use group boxes to group controls so that,
when a series of controls is needed, you can display its corresponding group of questions and
hide the other group box.

Practical Learning: Creating the Questions


1. To add a new form, on the main menu, click Project -> Add Windows Form...
2. In the Add New Item dialog box, set the Name QuestionAnswer
3. Click Add
4. Design the form as follows:
Control Caption Name Additional Properties
Label Question lblQuestion
Multiline: True
TextBox txtQuestion
ScrollBars: Vertical
Group Box grpSingleAnswers
AutoSize: False
Radio Button rdoAnswer1 CheckAlign: TopLeft
TextAlign: TopLeft
AutoSize: False
CheckAlign:
Radio Button rdoAnswer2
TopLeft
TextAlign: TopLeft
AutoSize: False
CheckAlign:
Radio Button rdoAnswer3
TopLeft
TextAlign: TopLeft
AutoSize: False
CheckAlign:
Radio Button rdoAnswer4
TopLeft
TextAlign: TopLeft
Button Quit btnQuit
Button Check Answer btnCheckAnswer
ShowInTaskbar:
Form
false

5. On the Toolbox, click the RadioButton


6. On the form, click checkBox1
7. Set the properties of the new radioButton1 control as follows:
Name: rdoAnswer1
AutoSize: False
CheckAlign: TopLeft
TextAlign: TopLeft
8. On the Toolbox, click the RadioButton
9. On the form, click checkBox2
10. Set the properties of the new radioButton1 control as follows:
Name: rdoAnswer2
AutoSize: False
CheckAlign: TopLeft
TextAlign: TopLeft
11. On the Toolbox, click the RadioButton
12. On the form, click checkBox3
13. Set the properties of the new radioButton1 control as follows:
Name: rdoAnswer3
AutoSize: False
CheckAlign: TopLeft
TextAlign: TopLeft
14. On the Toolbox, click the RadioButton
15. On the form, click checkBox4
16. Set the properties of the new radioButton1 control as follows:
Name: rdoAnswer4
AutoSize: False
CheckAlign: TopLeft
TextAlign: TopLeft
17. On the Toolbox, click the RadioButton
18. On the form, click checkBox5
19. Set the properties of the new radioButton1 control as follows:
Name: rdoAnswer5
AutoSize: False
CheckAlign: TopLeft
TextAlign: TopLeft
20. In the Add New Item dialog box, set the Name Experiment and press Enter
21. Enlarge the form enough and, on the main menu, click Edit -> Paste
22. Design the form as follows:
Control Caption Name Additional Properties
Group Box grpMultipleAnswers
AutoSize: False
CheckBox chkAnswer1 CheckAlign: TopLeft
TextAlign: TopLeft
AutoSize: False
CheckAlign:
CheckBox chkAnswer2
TopLeft
TextAlign: TopLeft
AutoSize: False
CheckAlign:
CheckBox chkAnswer3
TopLeft
TextAlign: TopLeft
AutoSize: False
CheckAlign:
CheckBox chkAnswer4
TopLeft
TextAlign: TopLeft

23. On the Experiment form, click the group box to select it


24. On the main menu, click Edit -> Copy
25. Display the QuestionAnswer form
26. Click an unoccupied area of the form to make sure no control (especially not
the group box) is select
27. On the main menu, click Edit -> Paste
28. Move the new group box to place it exactly on top of the other group box

29. On the form, double-click the Quit button


30. Make the following changes:

31. Return to the form


32. Double-click the Check Answer button and implement its event as follows:

33. Return to the form and double-click an unoccupied area of its body
34. Implement the event as follows:

35. Display the first form


36. Double-click the Start button and implement its event as follows:
37. Display the first form again
38. Double-click the Close button and implement its event as follows:

39. Execute the application to see the result

Rental Project :

ADO.NET Application: Bethesda Car


Rental
Introduction
It used to be an arduous process to create a database using Microsoft ActiveX Data Objects
(ADO). You had to know a great deal of the ADOX and ADO libraries. When Microsoft
developed the .NET Framework and the new process of creating a database through the
ADO.NET technique, database development was significantly simplified but you were still
required to write some code to perform some of the routine operations.

As implemented in Microsoft Visual Studio 2005, ADO.NET has become even easier, so easy that
you can create a complete functional graphical database with little or no code. To illustrate this,
we will create an application that would help a company that rents cars.

Employees
We will start our database with the list of employees of the company, who are people who
process daily rental transactions.

Practical Learning: Introducing the Application


1. To start the database, click Start -> All Programs -> Microsoft SQL Server 2005 -> SQL
Server Management Studio
2. Select or accept the Server Type, the Server Name, and the Authentication
3. Click Connect
4. Expand the Databases node
5. To create a new database, right-click the Databases node and click New Database...
6. Set the database name to bcr (which stands for Bethesda Car Rental) and accept the
default owner or change it
7. Click OK
8. Expand the bcr node and the Tables node under it
9. To create a new table, right the Tables node under bcr and click New Table...
10. Set the first column name to EmployeeID
11. Set its Data Type to int
12. In the lower section, expand Identity Specification and set the (Is Identify) field to Yes
13. On the Table Designer toolbar, click the Set Primary Key button
14. Complete the table with the following columns

Column Name Data Type Allow Nulls


EmployeeID int
FirstName varchar(30)
LastName varchar(30) Uncheck
Title varchar(50)
HourlySalary decimal(8,2)

15. Save the table as Employees and close it


16. In the Object Explorer, right-click dbo.Employees and click Open Table
17. Create the following records:

EmployeeID FirstName LastName Title HourlySalary


1 Patricia Katts Regional Manager 28.45
2 Julienne Mukoko Sales Manager 26.65
3 Bertrand Yamaguchi Sales Representative 12.85
4 Hermine Calhoun Sales Representative 11.95

18. Close the table


19. Microsoft Visual C++ 2005 or Microsoft Visual Studio
20. Create a Windows Application named bcr1
21. To change the name of the form, in the Solution Explorer, right-click Form1.cs and click
Rename
22. Type Central.cs and press Enter
23. To create a new form, on the main menu, click Project -> Add Windows Form...
24. Set the name to Employees and click Add
25. On the main menu, click Data -> Show Data Sources
26. Click Add New Data Source...
27. In the first page of the Data Source Configuration Wizard, make sure that Database is
selected and click Next
28. If a bcr connection appears in the combo box, fine; if not, click New Connection and create
a connection to the bcr database. Click Next
29. Change the name of the connection string to strBCRConnection and click Next
30. Expand the Tables node and click the check box of Employees
31. Change the DataSet Name to dsBCR

32. Click Finish


33. In the Data Sources window, click Employees and click the arrow of its combo box to select
DataGridView (it should be selected already as the default).
Drag the Employees node and drop it on the form
34. While the DataGridView control is still selected on the form, in the Properties window, click
the ellipsis of the Columns field and make the following changes:

Selected Columns HeaderText Width


EmployeeID Employee ID 75
FirstName First Name 80
LastName Last Name 80
Title 130
HourlySalary Hourly Salary 75

35. Click OK
36. Set DataGridView's Anchor property to Top, Bottom, Left, Right
37. Under the DataGridView control, add a button and set its properties as follows:
Text: Close
(Name): btnClose
Anchor: Bottom, Right

38. Double-click the Close button and implement its even as follows:

private void btnClose_Click(object sender, EventArgs e)


{
Close();
}
39. Access the Central form
40. Add a button to it and set its properties as follows:
Text: Employees
(Name): btnEmployees
41. Double-click the Employees button and implement its even as follows:

private void btnEmployees_Click(object sender, EventArgs e)


{
Employees frmEmployees = new Employees();
frmEmployees.ShowDialog();
}
42. Execute the application to test it
43. Access the Employees form
44. Using the + button, add the following employees:
EmployeeID FirstName LastName Title HourlySalary
5 Olivier Perez Personnel Manager 24.05
6 Henry James Sales Representative 12.05
7 Emile Bemba Sales Representative 14.15

45.

46. Close the forms

ADO.NET Application: Bethesda Car Rental


Customers
For a car rental company, the customers are the people or entities who rent cars. In a small
application, you can enter the customer's when processing a rental order. A better way is to
create a list of customers so that a repeating customer would have his or her records already in
the database.

Practical Learning: Introducing the Application


1. In the Microsoft SQL Server Management Studio, if necessary, expand the Databases,
the bcr, and the Tables node.
To create a new table, right the Tables node under bcr and click New Table...
2. Set the first column name to CustomerID
3. Set its Data Type to int
4. In the lower section, expand Identity Specification and set the (Is Identify) field to Yes
5. Right-click CustomerID and click Set Primary Key
6. Complete the table with the following columns

Column Name Data Type Allow Nulls


CustomerID int
DrvLicNbr varchar(50) Uncheck
FullName varchar(50) Uncheck
Address varchar(50)
City varchar(50)
State varchar(50)
ZIPCode varchar(20)
Country varchar(50)

7. Save the table as Customers and close it


8. In the Object Explorer, right-click dbo.Customers and click Open Table
9. Create a few records
10. In Microsoft Visual Studio, if necessary, open the bcr1 application created in the previous
section
11. In the Data Source window, right-click dsBCR and click Configure DataSet With Wizard...
12. Expand the Tables node and click the check box of Customers
13. Click Finish
14. To create a new form, on the main menu, click Project -> Add Windows Form...
15. Set the name to Customers and click Add
16. Drag the Customers node and drop it on the form
17. While the DataGridView control is still selected on the form, in the Properties window, click
the ellipsis of the Columns field and make the following changes:

Selected Columns HeaderText Width


CustomerID Customer ID 75
DrvLicNbr Drv. Lic. #
FullName Full Name
Address 130
City 80
State 50
ZIPCode ZIP Code 50
Country 50

18. Click OK
19. Set DataGridView's Anchor property to Top, Bottom, Left, Right
20. Under the DataGridView control, add a button and set its properties as follows:
Text: Close
(Name): btnClose
Anchor: Bottom, Right

21. Double-click the Close button and implement its even as follows:

System::Void btnClose_Click(System::Object^ sender,


System::EventArgs^ e)
{
Close();
}
22. Access the Central form
23. Add a button to it and set its properties as follows:
Text: Customers
(Name): btnCustomers
24. Double-click the Customers button
25. Implement the even as follows:

private void btnCustomers_Click(object sender, EventArgs e)


{
Customers frmCustomers = new Customers();
frmCustomers.ShowDialog();
}
26. Execute the application to test it
27. Display the Customers form
28. Close the form(s)

ADO.NET Application: Bethesda Car Rental


Cars
A car is the object that a customer comes to rent to a car rental company. You should have a list
company owns. There are usually two categories of information needed for a car. Basic informat
processing a rental order. On the other hand, at times, a customer may want some extended inform
or she is renting. Based on these, we will create one table of cars by different forms to access its info
on the task at hand.

Practical Learning: Introducing the Application


1. Save the following cars to a folder. This application assumes that you would have saved them to
inside of a folder name Programs in a computer named Training (and that the Programs folder i
2. In the Microsoft SQL Server Management Studio, if necessary, expand the Databases, the bcr
node.
To create a new table, right the Tables node under bcr and click New Table...
3. Set the first column name to CarID and set its Data Type to int
4. In the lower section, expand Identity Specification and set the (Is Identify) field to Yes
5. On the table, right-click CarID and click Set Primary Key
6. Complete the table with the following columns

Column Name Data Type Allow Nulls


CarID int
TagNumber varchar(50) Uncheck
Make varchar(50) Uncheck
Model varchar(50) Uncheck
CarYear int
Mileage int
Category varchar(50)
PictureName varchar(200)
K7Player bit
DVDPlayer bit
CDPlayer bit
Available bit Uncheck

7. Save the table as Cars and close it


8. In Microsoft Visual Studio, if necessary, open the bcr1 application created in the first section.
In the Data Source window, right-click dsBCR and click Configure DataSet With Wizard...
9. Expand the Tables node and click the check box of Cars
10. Click Finish
11. To create a new form, on the main menu, click Project . Add Windows Form...
12. Set the name to CarDetails and press Enter
13. Design the form as follows:

Additional
Control Text Name Modifiers
Properties
Label Tag Number:
TextBox txtTagNumber Public
Label Make:
TextBox txtMake Public
Label Model:
TextBox txtModel Public
Label Year:
AlignText:
TextBox txtYear Public
Right
Label Mileage
AlignText:
TextBox txtMileage Public
Right
Label Category:
Items:
Economy
Compact
Standard
ComboBox cboCategory Public Full Size
Mini Van
SUV
Truck
Van
CheckBox K7 Player chkK7Player Public
CheckBox DVD Player chkDVDPlayer Public
CheckBox CD Player chkCDPlayer Public
CheckBox Available chkAvailable Public
Image:
PictureBox pctCar
none.gif
TextBox \\Training\Programs\Cars\none.gif txtPictureName Public
Button Picture... chkPicture
DialogResult:
Button Submit btnSubmit
OK
Button Close btnClose

14. To create a new form, on the main menu, click Project . Add New Item...
15. In the Templates list, click Windows Form and set the name to CarsRecords
16. Click Add
17. Design the form as follows:

Control Text Name Additional Properties


Label Car ID:
TextBox txtCarID
Label Tag Number:
TextBox txtTagNumber
Label Make:
TextBox txtMake
Label Model:
TextBox txtModel
Label Year:
TextBox txtYear AlignText: Right
Label Mileage
TextBox txtMileage AlignText: Right
Label Category:
ComboBox cboCategory Items:
Economy
Compact
Standard
Full Size
Mini Van
SUV
Truck
Van
CheckBox K7 Player chkK7Player
CheckBox DVD Player chkDVDPlayer
CheckBox CD Player chkCDPlayer
CheckBox Available chkAvailable
PictureBox pctCar Image: none.gif
TextBox \\Training\Programs\Cars\none.gif txtPictureName
Button Picture... chkPicture Modifiers: Public
Button Close btnClose
Button New Car btnNewCar
Button First btnFirst
Button Previous btnPrevious
Button Next btnNext
Button Last btnLast

18. Return to the form


19. On the Toolbox, click DataSet In the Data section) and click the form
20. In the Add Dataset dialog box, accept the Typed dataset radio button and the contents of the Na
Click OK
21. In the (Data section of the) Toolbox, click BindingSource and click the form
22. In the Properties window, change its characteristics as follows:
Name: bsCars
DataSource: dsBCR1
DataMember: Cars
23. Click each control and set its data bindings
24. On the Toolbox, click the OpenFileDialog button and click the form
25. Set its name to dlgPicture
26. Set its Filter to
Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All files (*.*)|*.*
27. Double-click the Picture button and implement its event as follows:

private void btnPicture_Click(object sender, EventArgs e)


{
if( dlgPicture.ShowDialog() == DialogResult.OK )
{
txtPictureName.Text = dlgPicture.FileName;
pctCar.Image = Image.FromFile(txtPictureName.Text);
}

}
28. Return to the form
29. Double-click the Close button and implement its event as follows:

private void btnClose_Click(object sender, EventArgs e)


{
Close();
}
30. Return to the form
31. Double-click the New Car button and implement the event as follows:

private void btnNewCar_Click(object sender, EventArgs e)


{
CarDetails dlgCar = new CarDetails();

dlgCar.btnPicture.Visible = true;
dlgCar.btnSubmit.Visible = true;

if( dlgCar.ShowDialog() == DialogResult.OK )


{
if( dlgCar.txtTagNumber.Text == "" )
{
MessageBox.Show("You must specify the tag number of the car\n"
+
"The record will not be created");
return;
}
if( dlgCar.txtMake.Text == "" )
{
MessageBox.Show("You must specify the car make\n" +
"The record will not be created");
return;
}
if( dlgCar.txtModel.Text == "" )
{
MessageBox.Show("You must specify the car model\n" +
"The record will not be
created");
return;
}
if( dlgCar.txtYear.Text == "" )
{
MessageBox.Show("You must specify the year of the
car\n" +
"The record will not be
created");
return;
}

string strNewCar = string.Concat("INSERT INTO Cars(TagNumber, Make,


",
"Model, CarYear, Mileage, Category,
",
"PictureName, K7Player, DVDPlayer, ",
"CDPlayer, Available) VALUES('",
dlgCar.txtTagNumber.Text, "', '",
dlgCar.txtMake.Text, "', '",
dlgCar.txtModel.Text, "', '",
dlgCar.txtYear.Text, "', '",
dlgCar.txtMileage.Text, "', '",
dlgCar.cboCategory.Text, "', '",
dlgCar.txtPictureName.Text, "', '",
dlgCar.chkK7Player.Checked, "', '",
dlgCar.chkDVDPlayer.Checked, "', '",
dlgCar.chkCDPlayer.Checked, "', '",
dlgCar.chkAvailable.Checked, "')");

System.Data.SqlClient.SqlConnection conCar =
new System.Data.SqlClient.SqlConnection("Data Source=" +
"(local);Database=bcr;Integrated
Security=yes");
System.Data.SqlClient.SqlCommand cmdCar =
new System.Data.SqlClient.SqlCommand(strNewCar, conCar);

conCar.Open();
cmdCar.ExecuteNonQuery();
conCar.Close();
}
}
32. Return to the form and double-click the First button
33. Implement its event as follows:

private void btnFirst_Click(object sender, System.EventArgs e)


{
bsCars.MoveFirst();
this.pctCar.Image = Image.FromFile(txtPictureName.Text);

// This section is used to save the record


// if the user had changed anything before moving on
this.Validate();
this.bsCars.EndEdit();
this.CarsTableAdapter.Update(this.dsOrder1.Cars);
}
34. Return to the form and double-click the Previous button
35. Implement its event as follows:

private void btnPrevious_Click(object sender, System.EventArgs e)


{
bsCars.MovePrevious();
this.pctCar.Image = Image.FromFile(txtPictureName.Text);

this.Validate();
this.bsCars.EndEdit();
this.CarsTableAdapter.Update(this.dsOrder1.Cars);
}
36. Return to the form and double-click the Next button
37. Implement its event as follows:

private void btnNext_Click(object sender, System.EventArgs e)


{
bsCars.MoveNext();
this.pctCar.Image = Image.FromFile(txtPictureName.Text);

this.Validate();
this.bsCars.EndEdit();
this.CarsTableAdapter.Update(this.dsOrder1.Cars);
}
38. Return to the form and double-click the Last button
39. Implement its event as follows:

private void btnLast_Click(object sender, System.EventArgs e)


{
bsCars.MoveLast();
this.pctCar.Image = Image.FromFile(txtPictureName.Text);

this.Validate();
this.bsCars.EndEdit();
this.CarsTableAdapter.Update(this.dsOrder1.Cars);
}
40. Return to the form and double-click the Close button
41. Implement its event as follows:

private void btnClose_Click(object sender, EventArgs e)


{
Close();
}
42. Access the first form
43. Add a button to it and set its properties as follows:
Text: Cars Review
Name: btnCarsReview
44. Double-click the Cars Review button and implement the event as follows:

private void btnCarsReview_Click(object sender, System.EventArgs e)


{
CarsRecords frmCarsRecords = new CarsRecords;
frmCarsRecords.ShowDialog();
}
45. Execute the application to test it
46. Using the New Car form Create a few records
47. Close the form(s)
ADO.NET Application: Bethesda Car
Rental
Order Processing
After creating the accessory objects of a database, you can get the application to perform the
actual transactions. For a car rental company, we will create the object used to process the
regular rental transactions.

Practical Learning: Introducing the Application


1. In the Microsoft SQL Server Management Studio, if necessary, expand the Databases, the
bcr, and the Tables node.
To create a new table, right the Tables node under bcr and click New Table...
2. Set the first column name to OrderProcessingID
3. Set its Data Type to int
4. In the lower section, expand Identity Specification and set the (Is Identify) field to Yes
5. On the Table Designer toolbar, click the Set Primary Key button
6. Complete the table with the following columns

Column Name Data Type Allow Nulls


OrderProcessingID int
OrderDate varchar(50)
OrderTime varchar(50)
EmployeeID int Uncheck
CustomerID int Uncheck
CarID int Uncheck
CarCondition varchar(20)
TankLevel varchar(50)
StartDate varchar(50) Uncheck
EndDate varchar(50)
NumberOfDays varchar(50)
RateApplied varchar(50)
SubTotal varchar(50)
TaxRate varchar(50)
TaxAmount varchar(50)
RentTotal varchar(50)
Notes varchar(255)

7. Save the table as OrderProcessing


8. Right-click the table and click Relationships...
9. Click Add
10. Click Tables and Columns Specification and click its ellipsis button
11. Under Primary Key Table, select Employees and, under Employees, select EmployeeID
12. Under OrderProcessing, select EmployeeID
13. Click OK
14. Click Add again
15. Click the ellipsis button of Tables and Columns Specification
16. Under Primary Key Table, select Customers and, under Employees, select CustomerID
17. Under OrderProcessing, select CustomerID
18. Click OK
19. Click Add
20. Click the ellipsis button of Tables and Columns Specification
21. Under Primary Key Table, select Cars and, under Cars, select CarID
22. Click OK
23. Click Close
24. Close the table
25. When asked whether you want to save it, click Yes and Yes
26. To create a view, in the Object Explorer under bcr, right-click Views and click New View...
27. In the Add Table dialog box, click Employees
28. Click Add and click Close
29. In the Diagram pane (the top section), click the check box of EmployeeID
30. In the SQL pane, on the right side of SELECT EmployeeID, add
LastName + ', ' + FirstName AS FullName
31. Save the view as EmployeesNames
32. Close it
33. In Microsoft Visual Studio, if necessary, open the bcr1 application created in the first
section
In the Data Source window, right-click dsBCR and click Configure DataSet With Wizard...
34. Expand the Tables node and click the check box of OrderProcessing
35. Expand the Views node and click the check box of EmployeesNames
36. Click Finish
37. To create a new form, on the main menu, click Project . Add Windows Form...
38. Set the name to OrderProcessing and click Add
39. Enlarge and heighten the form
40. In the Data Sources window, click OrderProcessing and click the arrow of its combo box
41. Select Details
42. From the Data Sources window, drag OrderProcessing and drop it on the form
43. While the controls are still selected, move them to the left side of the form (to create an
empty space in the middle and on the right side of the form)
44. Again, from the Data Sources window, drag Employees and drop it on the form
45. While the DataGridView control is still selected on the form, press Delete to remove it from
the form
46. Once again, from the Data Sources window, drag Customers and drop it in an empty area
of the form
47. While the DataGridView control is still selected on the form, press Delete to remove it from
the form
48. Once again, from the Data Sources window, drag Cars and drop it on the form
49. While the new controls are still selected on the form, press Delete to remove them from
the form
50. Once again, from the Data Sources window, drag EmployeesNames and drop it on the form
51. While the DataGridView control is still selected on the form, press Delete to remove it
52. Delete the text boxes of OrderDate, OrderTime, EmployeeID, CustomerID, CarID,
CarCondition, TankLevel, StartDate, and EndDate
53. Design the form as follows (you will add new controls to replace those that were deleted):
Control Text Name Additional Properties
Label Processed By:
ComboBox cboEmployeeID
Label Order Processing ID:
TextBox
Label Order Date:
DateTimePicker dtpOrderDate
Label Order Time:
Format: Time
DateTimePicker dtpOrderTime
ShowUpDown: True
GroupBox Customer
Label Select:
ComboBox cboCustomerID
Label Name:
TextBox txtCustomerName
Label Address:
TextBox txtCustomerAddress
TextBox txtCustomerCity
TextBox txtCustomerState
TextBox txtCustomerZIPCode
TextBox txtCustomerCountry
GroupBox Car
Label Select:
ComboBox cboCarID
Button Details btnCar Details
Label Make:
TextBox txtCarMake
Label Model:
TextBox txtCarModel
Label Year:
TextBox txtCarYear
Label Mileage:
TextBox txtCarMileage
Label Car Condition:
Items:
Excellent
ComboBox cboCarConditions Good
Driveable
Needs Repair
Label Tank Level:
Items:
Empty
ComboBox cboTankLevels 1/4 Empty
Half
3/4 Full
Full Tank
Label Start Date:
DateTimePicker dtpStartRent
Label End Time:
DateTimePicker dtpEndRent
Label Notes:
Multiline: True
TextBox
ScrollBars: Vertical
Label Rate Applied:
Text: 0.00
TextBox
TextAlign: Right
Label Number Of Days:
Text: 0
TextBox
TextAlign: Right
Label Sub Total:
Text: 0.00
TextBox
TextAlign: Right
Label Tax Rate:
Text: 5.75
TextBox
TextAlign: Right
Label %
Label Tax Amount:
Text: 0.00
TextBox
TextAlign: Right
Label Rent Total:
Text: 0.00
TextBox
TextAlign: Right
Button Close btnClose

54. Click each control that was added and change its data bindings
55. On the form, double-click the Details button in the Cars section and implement its Click
event as follows:

private void btnCarDetails_Click(object sender, EventArgs e)


{
if (cboCarID.Text == "")
MessageBox.Show("No car is currently selected");
else
{
CarDetails frmCarDetails = new CarDetails();
string strCar =
string.Concat("SELECT * FROM Cars WHERE TagNumber
= '",
cboCarID.Text, "'");
System.Data.SqlClient.SqlConnection conCar =
new System.Data.SqlClient.SqlConnection(
"Data Source=(local);Database=bcr;Integrated
Security=yes");
System.Data.SqlClient.SqlCommand cmdCar =
new System.Data.SqlClient.SqlCommand(strCar,
conCar);
conCar.Open();

System.Data.SqlClient.SqlDataReader rdrCar =
cmdCar.ExecuteReader();

while (rdrCar.Read())
{
frmCarDetails.txtTagNumber.Text = rdrCar.GetString(1);
frmCarDetails.txtMake.Text = rdrCar.GetString(2);
frmCarDetails.txtModel.Text = rdrCar.GetString(3);
frmCarDetails.txtYear.Text =
rdrCar.GetInt32(4).ToString();
frmCarDetails.txtMileage.Text =
rdrCar.GetInt32(5).ToString();
frmCarDetails.cboCategory.Text = rdrCar.GetString(6);
frmCarDetails.txtPictureName.Text = rdrCar.GetString(7);
frmCarDetails.chkK7Player.Checked = rdrCar.GetBoolean(8);
frmCarDetails.chkDVDPlayer.Checked =
rdrCar.GetBoolean(9);
frmCarDetails.chkCDPlayer.Checked =
rdrCar.GetBoolean(10);
frmCarDetails.chkAvailable.Checked =
rdrCar.GetBoolean(11);
frmCarDetails.pctCar.Image =
Image.FromFile(frmCarDetails.txtPictureName.Text);
}

frmCarDetails.btnPicture.Visible = false;
frmCarDetails.btnSubmit.Visible = false;
frmCarDetails.ShowDialog();
conCar.Close();
}
}
56. Return to the OrderProcessing form, click the text box on the right side of Number Of Days
57. In the Properties window, click the Events box and generate the event of the Leave field
58. Define it as follows:

private void numberOfDaysTextBox_Leave(object sender, EventArgs e)


{
int numberOfDays = 0;
decimal rateApplied = 0.00M, subTotal = 0.00M;

try {
rateApplied = decimal.Parse(rateAppliedTextBox.Text);
}
catch(FormatException )
{
MessageBox.Show("Invalid value for the rate applied");
}

try {
numberOfDays = int.Parse(numberOfDaysTextBox.Text);
}
catch(FormatException )
{
MessageBox.Show("Invalid value for the number of days");
}

subTotal = rateApplied * numberOfDays;


subTotalTextBox.Text = subTotal.ToString("F");
}
59. Return to OrderProcessing the form, click the text box on the right side of Tax Rate
60. In the Events section of the Properties window, generate the event of the Leave field
61. Define it as follows:

private void taxRateTextBox_Leave(object sender, EventArgs e)


{
decimal subTotal = 0.00M, taxRate = 0.00M,
taxAmount = 0.00M, rentTotal = 0.00M;

try {
subTotal = decimal.Parse(subTotalTextBox.Text);
}
catch(FormatException )
{
MessageBox.Show("Invalid value for sub-tota");
}

try {
taxRate = decimal.Parse(taxRateTextBox.Text);
}
catch(FormatException )
{
MessageBox.Show("Invalid value for the tax rate");
}

taxAmount = subTotal * taxRate / 100;


rentTotal = subTotal + taxAmount;

taxAmountTextBox.Text = taxAmount.ToString("F");
rentTotalTextBox.Text = rentTotal.ToString("F");
}
62. Return to OrderProcessing the form and double-click the Close button
63. Implement its even as follows:

private void btnClose_Click(object sender, EventArgs e)


{
Close();
}
64. Access the Central form
65. Add a button to it and set its properties as follows:
Text: OrderProcessing
(Name): btnOrderProcessing
66. Double-click the Customers button
67. In the top section of the file, under the #pragma once line, type
#include "OrderProcessing.h"
68. Scroll to the bottom of the file and implement the even as follows:

private void btnOrderProcessing_Click(object sender, EventArgs e)


{
OrderProcessing frmOrder = new OrderProcessing();
frmOrder.ShowDialog();
}
69. Execute the application to test it
70. Display the OrderProcessing form
71. To process an order, click the + button and complete the form

72. After completing the form, click the Save button


73. Close the form(s)

Bank Project :

Example Application: Yugo National Bank


Introduction
This is an introduction to bank applications. It is a Microsoft SQL Server
database. The interface objects made of forms are designed using Microsoft
Visual Studio. This means that, to follow the instructions in these lessons,
you should have Microsoft SQL Server 2005 (the application was not tested
on the smaller version of the database server). You should also have
Microsoft Visual Studio 2005 Professional (the Express versions were not
tested but they may as well work).
This section introduces the application. It instructs your to create the database and the regular object
the users will use (forms).

Practical Learning: Introducing Views


1. Start Microsoft Visual C# and create a new Windows Application named YugoNationalBank1
2. In the Solution Explorer, right-click Form1.cs and click Rename
3. Type Central.cs and press Enter
4. Double-click the middle of the form and implement the Load event as follows:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace YugoNationalBank1
{
public partial class Exercise : Form
{
public Exercise()
{
InitializeComponent();
}

void CreateDatabase()
{
string strAction = "";
SqlConnection cnnYNB = null;
SqlCommand cmdYNB = null;

using (cnnYNB = new SqlConnection("Data Source=(local); "


+
"Integrated Security='SSPI';"))
{
strAction = "IF EXISTS ( " +
"SELECT name " +
"FROM sys.databases " +
"WHERE name = N'YugoNationalBank1') " +
"DROP DATABASE YugoNationalBank1; " +
"CREATE DATABASE YugoNationalBank1";

cmdYNB = new SqlCommand(strAction, cnnYNB);

cnnYNB.Open();
cmdYNB.ExecuteNonQuery();

MessageBox.Show("A database named YugoNationalBank1 "


+
"has been created.", "Yugo National Bank");
Compound Interest :

Example Application:
The Compound Interest

Introduction
The application we are going to create is used to calculate the amount owed
on a loan using the principal, the interest rate, and the period.

Windows Controls:

• Label
• Text Box
• Radio Buttons

Practical Learning: Creating the Application


1. Start a new Windows Application named CompoundInterest1
2. Design the form as followed:
Control Name Text Additional Properties

GroupBox Loan Setup

Label Principal:

TextBox txtPrincipal 0.00 TextAlign: Right

Label Interest Rate:

TextBox txtInterestRate 8.25 TextAlign: Right

Label %

Label Number of Periods:

TextBox txtPeriods 1 TextAlign: Text

Label years

GroupBox Compound Frequency

RadioButton rdoMonthly

RadioButton rdoQuarterly

RadioButton rdoSemiannually

RadioButton rdoAnnually

GroupBox Results

Label Interest Earned:


TextAlign: Right
TextBox txtInterestEarned 0.00
ReadOnly: True

Label Amount Earned:

TextAlign: Right
TextBox txtFutureValue 0.00
ReadOnly: True

Button btnCalculate Calculate

Button btnClose Close

3. Test the application


1. On the form, click Monthly
2. In the Properties window, double-click Checked to set its value to True
3. On the form, double-click the Calculate button and implement its Click() event as follows:

private void btnCalculate_Click(object sender, EventArgs e)


{
double principal = 0.00,
interestRate = 0.00,
interestEarned = 0.00;
double futureValue = 0.00,
ratePerPeriod = 0.00,
periods = 0;
int compoundType = 0;

// Retrieve the value of the principal


try
{
principal = double.Parse(txtPrincipal.Text);
}
catch (FormatException)
{
MessageBox.Show("The value you entered for the principal " +
"is not valid\nPlease try again");
}

// Retrieve the interest rate


try
{
interestRate = double.Parse(txtInterestRate.Text) / 100;
}
catch (FormatException)
{
MessageBox.Show("The value you entered for the interest " +
"rate is not valid\nPlease try again");
}

// Find out what radio button was clicked to


// apply the compound frequency
if (rdoMonthly.Checked)
compoundType = 12;
else if (rdoQuarterly.Checked)
compoundType = 4;
else if (rdoSemiannually.Checked)
compoundType = 2;
else
compoundType = 1;

// Get the number of periods


try
{
periods = double.Parse(txtPeriods.Text);
}
catch (FormatException)
{
MessageBox.Show("The value you entered for the number " +
"of periods is not valid\nPlease try again");
}

// These values will make the calculation easier to read


double i = interestRate / compoundType;
double n = compoundType * periods;

// Perform the necessary calculations


ratePerPeriod = interestRate / periods;
futureValue = principal * Math.Pow(1 + i, n);
interestEarned = futureValue - principal;

// Display the values in the appropriate text boxes


txtInterestEarned.Text = interestEarned.ToString("C");
txtFutureValue.Text = futureValue.ToString("C");
}
4. On the form, double-click the Close button and implement its OnClick() event as follows:

private void btnClose_Click(object sender, EventArgs e)


{
Close();
}

5. Test the application


6. After using it, close the form and return to your programming environment

Charts:

GDI+ Application: Weekly Sales

Description
This is an example of a vertical rectangular chart. To draw the rectangles,
we use simple solid brushes.

Windows Controls:

• Label
• Button
• Text Box

Practical Learning: Using a Solid Brush


1. Start a new Windows Forms Application named WeeklySales2
2. Design the form as follows:

Control Name Text Other Properties

Label Monday

Label Tuesday

Label Wednesday

Label Thursday

Label Friday
TextBox txtMonday 12000 TextAlign: Right

TextBox txtTuesday 11000 TextAlign: Right

TextBox txtWednesday 8500 TextAlign: Right

TextBox txtThursday 16800 TextAlign: Right

TextBox txtFriday 17500 TextAlign: Right

Button Generate btnGenerate

3. Double-click an unoccupied area of the form and change the file as follows:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WeeklySales2
{
public partial class Form1 : Form
{
Graphics graphDrawingArea;
Bitmap bmpDrawingArea;

public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
bmpDrawingArea = new Bitmap(Width, Height);
graphDrawingArea = Graphics.FromImage(bmpDrawingArea);
}
}
}

4. Return to the form and click an empty area on it. In the Properties window, click the
Events button
5. Double-click the Paint field and implement its event as follows:

private void Form1_Paint(object sender, PaintEventArgs e)


{
e.Graphics.DrawImage(bmpDrawingArea, 0, 0);
}
6. Return to the form and double-click the Generate button
7. Implement its Click event as follows:

private void btnGenerate_Click(object sender, EventArgs e)


{
int monday = 0;
int tuesday = 0;
int wednesday = 0;
int thursday = 0;
int friday = 0;

try
{
monday = int.Parse(txtMonday.Text) / 100;
}
catch (FormatException)
{
MessageBox.Show("Invalid value");
}

try
{
tuesday = int.Parse(txtTuesday.Text) / 100;
}
catch (FormatException)
{
MessageBox.Show("Invalid value");
}

try
{
wednesday = int.Parse(txtWednesday.Text) / 100;
}
catch (FormatException)
{
MessageBox.Show("Invalid value");
}

try
{
thursday = int.Parse(txtThursday.Text) / 100;
}
catch (FormatException)
{
MessageBox.Show("Invalid value");
}

try
{
friday = int.Parse(txtFriday.Text) / 100;
}
catch (FormatException)
{
MessageBox.Show("Invalid value");
}
graphDrawingArea.Clear(this.BackColor);

graphDrawingArea.FillRectangle(new SolidBrush(Color.Red),
this.txtMonday.Left + 5,
280 - monday, 40, monday);
graphDrawingArea.DrawRectangle(new Pen(Color.Black),
this.txtMonday.Left + 5,
280 - monday, 40, monday);
graphDrawingArea.FillRectangle(new
SolidBrush(Color.Blue),
this.txtTuesday.Left + 5,
280 - tuesday, 40, tuesday);
graphDrawingArea.DrawRectangle(new Pen(Color.Black),
this.txtTuesday.Left + 5,
280 - tuesday, 40, tuesday);
graphDrawingArea.FillRectangle(new
SolidBrush(Color.Fuchsia),
this.txtWednesday.Left + 5,
280 - wednesday, 40, wednesday);
graphDrawingArea.DrawRectangle(new Pen(Color.Black),
this.txtWednesday.Left + 5,
280 - wednesday, 40, wednesday);
graphDrawingArea.FillRectangle(new
SolidBrush(Color.Brown),
this.txtThursday.Left + 5,
280 - thursday, 40, thursday);
graphDrawingArea.DrawRectangle(new Pen(Color.Black),
this.txtThursday.Left + 5,
280 - thursday, 40, thursday);
graphDrawingArea.FillRectangle(new
SolidBrush(Color.Turquoise),
this.txtFriday.Left + 5,
280 - friday, 40, friday);
graphDrawingArea.DrawRectangle(new Pen(Color.Black),
this.txtFriday.Left + 5,
280 - friday, 40, friday);

graphDrawingArea.DrawRectangle(new Pen(Color.Black),
10, 280, Width - 30, 1);
Invalidate();
}

8. Execute the application and test the form


9. After using it, close the form

Charts:

GDI+ Application: Yearly Sales


Introduction
This is an example of a vertical rectangular chart. To draw the rectangles,
we use hatch brushes.

Windows Controls:

• Label
• Button
• Text Box
• Group Box

Practical Learning: Using a Hatch Brush


1. Start a new Windows Forms Application named YearlySales2
2. Design the form as follows:
Control Name Text

GroupBox Current Year's Sales

Label 1st Qtr

Label 2nd Qtr

Label 3rd Qtr

Label 4th Qtr

TextBox txtCurrentQtr1 0

TextBox txtCurrentQtr2 0

TextBox txtCurrentQtr3 0

TextBox txtCurrentQtr4 0

Button Close btnClose

GroupBox Previous Year's Sales


Label 1st Qtr

Label 2nd Qtr

Label 3rd Qtr

Label 4th Qtr

TextBox txtPreviousQtr1 0

TextBox txtPreviousQtr2 0

TextBox txtPreviousQtr3 0

TextBox txtPreviousQtr4 0

Button Generate btnGenerate

Label _________ Legend _________

Label This Year's Sales

Label Last Year's Sales

3. Double-click an unoccupied area of the form and change the file as follows:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;

namespace YearlySales2
{
public partial class Form1 : Form
{
Graphics graphDrawingArea;
Bitmap bmpDrawingArea;

public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
bmpDrawingArea = new Bitmap(Width, Height);
graphDrawingArea = Graphics.FromImage(bmpDrawingArea);
}
}
}

4. Return to the form and click an empty area on it. In the Properties window, click the Events butto
5. Double-click the Paint field and implement its event as follows:

private void Form1_Paint(object sender, PaintEventArgs e)


{
e.Graphics.DrawImage(bmpDrawingArea, 0, 0);
}
6. Return to the form and double-click the Generate button
7. Implement the event as follows:

private void btnGenerate_Click(object sender, EventArgs e)


{
// Retrieve the values of the current year's sales
int curQtr1 = 0;
int curQtr2 = 0;
int curQtr3 = 0;
int curQtr4 = 0;

try
{
curQtr1 = int.Parse(txtCurrentQtr1.Text) / 100;
}
catch (FormatException)
{
MessageBox.Show("Invalid Value");
}

try
{
curQtr2 = int.Parse(txtCurrentQtr2.Text) / 100;
}
catch (FormatException)
{
MessageBox.Show("Invalid Value");
}

try
{
curQtr3 = int.Parse(txtCurrentQtr3.Text) / 100;
}
catch (FormatException)
{
MessageBox.Show("Invalid Value");
}

try
{
curQtr4 = int.Parse(txtCurrentQtr4.Text) / 100;
}
catch (FormatException)
{
MessageBox.Show("Invalid Value");
}

// Create an array of Rectangle objects for the current


year
Rectangle[] rectCurrentYear =
{
new Rectangle(this.txtCurrentQtr1.Left+20,
380-curQtr1, 40, curQtr1),
new Rectangle(this.txtCurrentQtr2.Left+20,
380-curQtr2, 40, curQtr2),
new Rectangle(this.txtCurrentQtr3.Left+20,
380-curQtr3, 40, curQtr3),
new Rectangle(this.txtCurrentQtr4.Left+20,
380-curQtr4, 40, curQtr4)
};

// Retrieve the values of last year's sales


int prvQtr1 = 0;
int prvQtr2 = 0;
int prvQtr3 = 0;
int prvQtr4 = 0;

try
{
prvQtr1 = int.Parse(txtPreviousQtr1.Text) / 100;
}
catch (FormatException)
{
MessageBox.Show("Invalid Value");
}

try
{
prvQtr2 = int.Parse(txtPreviousQtr2.Text) / 100;
}
catch (FormatException)
{
MessageBox.Show("Invalid Value");
}

try
{
prvQtr3 = int.Parse(txtPreviousQtr3.Text) / 100;
}
catch (FormatException)
{
MessageBox.Show("Invalid Value");
}

try
{
prvQtr4 = int.Parse(txtPreviousQtr4.Text) / 100;
}
catch (FormatException)
{
MessageBox.Show("Invalid Value");
}

// Create an array of Rectangle objects for the previous


year
Rectangle[] rectPreviousYear =
{
new Rectangle(this.txtPreviousQtr1.Left+30,
380-prvQtr1, 40, prvQtr1),
new Rectangle(this.txtPreviousQtr2.Left+30,
380-prvQtr2, 40, prvQtr2),
new Rectangle(this.txtPreviousQtr3.Left+30,
380-prvQtr3, 40, prvQtr3),
new Rectangle(this.txtPreviousQtr4.Left+30,
380-prvQtr4, 40, prvQtr4)
};

// In case the user has changed the values, erase the previous
chart
graphDrawingArea.Clear(this.BackColor);

HatchBrush brushDiagCross =
new HatchBrush(HatchStyle.DiagonalCross,
Color.White, Color.Blue);
HatchBrush brushDotDiamond =
new HatchBrush(HatchStyle.DottedDiamond,
Color.Fuchsia, Color.Brown);

// Draw the chart for the previous year first to send it


back
graphDrawingArea.FillRectangles(brushDiagCross,
rectPreviousYear);
graphDrawingArea.DrawRectangles(new Pen(Color.Blue),
rectPreviousYear);
// Draw the chart for the current year in front
graphDrawingArea.FillRectangles(brushDotDiamond,
rectCurrentYear);
graphDrawingArea.DrawRectangles(new Pen(Color.Red),
rectCurrentYear);

// Draw the small rectangles of the legend


graphDrawingArea.FillRectangle(brushDotDiamond,
this.lblCurYear.Left - 30,
this.lblCurYear.Top, 20, 14);
graphDrawingArea.DrawRectangle(new Pen(Color.Red),
this.lblCurYear.Left - 30,
this.lblCurYear.Top, 20, 14);
graphDrawingArea.FillRectangle(brushDiagCross,
this.lblLastYear.Left - 30,
this.lblLastYear.Top, 20, 14);
graphDrawingArea.DrawRectangle(new Pen(Color.Blue),
this.lblLastYear.Left - 30,
this.lblLastYear.Top, 20, 14);

graphDrawingArea.DrawRectangle(new Pen(Color.Black),
25, 380, Width - 220, 1);
Invalidate();
}
8. Return to the form. Double-click the Close button and implement its Click event as follows:

private void btnClose_Click(object sender, EventArgs e)


{
Close();
}

9. Execute the application and test the form

10. After using it, close the form


11. Change the Paint event of the form as follows:

private void btnGenerate_Click(object sender, EventArgs e)


{
// Retrieve the values of the current year's sales
int curQtr1 = 0;
int curQtr2 = 0;
int curQtr3 = 0;
int curQtr4 = 0;

try
{
curQtr1 = int.Parse(txtCurrentQtr1.Text) / 100;
}
catch (FormatException)
{
MessageBox.Show("Invalid Value");
}

try
{
curQtr2 = int.Parse(txtCurrentQtr2.Text) / 100;
}
catch (FormatException)
{
MessageBox.Show("Invalid Value");
}

try
{
curQtr3 = int.Parse(txtCurrentQtr3.Text) / 100;
}
catch (FormatException)
{
MessageBox.Show("Invalid Value");
}

try
{
curQtr4 = int.Parse(txtCurrentQtr4.Text) / 100;
}
catch (FormatException)
{
MessageBox.Show("Invalid Value");
}

// Create an array of Rectangle objects for the current year


Rectangle[] rectCurrentYear =
{
new Rectangle(this.txtCurrentQtr1.Left+20,
380-curQtr1, 40, curQtr1),
new Rectangle(this.txtCurrentQtr2.Left+20,
380-curQtr2, 40, curQtr2),
new Rectangle(this.txtCurrentQtr3.Left+20,
380-curQtr3, 40, curQtr3),
new Rectangle(this.txtCurrentQtr4.Left+20,
380-curQtr4, 40, curQtr4)
};

// Retrieve the values of last year's sales


int prvQtr1 = 0;
int prvQtr2 = 0;
int prvQtr3 = 0;
int prvQtr4 = 0;

try
{
prvQtr1 = int.Parse(txtPreviousQtr1.Text) / 100;
}
catch (FormatException)
{
MessageBox.Show("Invalid Value");
}

try
{
prvQtr2 = int.Parse(txtPreviousQtr2.Text) / 100;
}
catch (FormatException)
{
MessageBox.Show("Invalid Value");
}

try
{
prvQtr3 = int.Parse(txtPreviousQtr3.Text) / 100;
}
catch (FormatException)
{
MessageBox.Show("Invalid Value");
}

try
{
prvQtr4 = int.Parse(txtPreviousQtr4.Text) / 100;
}
catch (FormatException)
{
MessageBox.Show("Invalid Value");
}

// Create an array of Rectangle objects for the previous year


Rectangle[] rectPreviousYear =
{
new Rectangle(this.txtPreviousQtr1.Left+30,
380-prvQtr1, 40, prvQtr1),
new Rectangle(this.txtPreviousQtr2.Left+30,
380-prvQtr2, 40, prvQtr2),
new Rectangle(this.txtPreviousQtr3.Left+30,
380-prvQtr3, 40, prvQtr3),
new Rectangle(this.txtPreviousQtr4.Left+30,
380-prvQtr4, 40, prvQtr4)
};

// In case the user has changed the values, erase the previous chart
graphDrawingArea.Clear(this.BackColor);

Rectangle rect = new Rectangle(10, 190, 300, 210);


LinearGradientBrush linGradBrush =
new LinearGradientBrush(rect,
Color.FromArgb(204, 102, 0),
Color.AntiqueWhite,
LinearGradientMode.Vertical);
graphDrawingArea.FillRectangle(linGradBrush, rect);
graphDrawingArea.DrawRectangle(new Pen(Color.Black), rect);

HatchBrush brushDiagCross =
new HatchBrush(HatchStyle.DiagonalCross,
Color.White, Color.Blue);
HatchBrush brushDotDiamond =
new HatchBrush(HatchStyle.DottedDiamond,
Color.Fuchsia, Color.Brown);

// Draw the chart for the previous year first to send it back
graphDrawingArea.FillRectangles(brushDiagCross,
rectPreviousYear);
graphDrawingArea.DrawRectangles(new Pen(Color.Blue),
rectPreviousYear);
// Draw the chart for the current year in front
graphDrawingArea.FillRectangles(brushDotDiamond,
rectCurrentYear);
graphDrawingArea.DrawRectangles(new Pen(Color.Red),
rectCurrentYear);

// Draw the small rectangles of the legend


graphDrawingArea.FillRectangle(brushDotDiamond,
this.lblCurYear.Left - 30,
this.lblCurYear.Top, 20, 14);
graphDrawingArea.DrawRectangle(new Pen(Color.Red),
this.lblCurYear.Left - 30,
this.lblCurYear.Top, 20, 14);
graphDrawingArea.FillRectangle(brushDiagCross,
this.lblLastYear.Left - 30,
this.lblLastYear.Top, 20, 14);
graphDrawingArea.DrawRectangle(new Pen(Color.Blue),
this.lblLastYear.Left - 30,
this.lblLastYear.Top, 20, 14);

graphDrawingArea.DrawRectangle(new Pen(Color.Black),
25, 380, Width - 220, 1);
Invalidate();
}

12. Execute the application to test it:


13. After using the form, close it

Bar Charts:

GDI+ Texture Brushes


Introduction
This is an example of drawing a pie chart in GDI+.

Windows Controls:

• Label
• Button
• Text Box
• Picture Box

Practical Learning: Using Texture Brushes


1. Start a new Windows Forms Application named SchoolEnrolment1
2. Design the form as follows:
Control Name Text
Enrolment / Program
Label
___________________________

Label Graduates

Label Undergraduates

Label Certificates

TextBox txtGraduates 0

TextBox txtUndergraduates 0

TextBox txtCertificates 0

Button btnCreateChart Create Chart

PictureBox pbxChart

Label ____Legend____

Label lblGraduates Graduates

Label lblUndergraduates Undergraduates

Label lblCertificates Certificates

Button btnClose Close


3. To design a bitmap, on the main menu, click Project -> Add New Item...
4. In the Templates list, click Bitmap File
5. Change the Name to graduates and click Add
6. To change the file location of the bitmap, on the main menu, click File -> Save graduates.bmp As
7. Locate and display the SchoolEnrolment2\SchoolEnrolment2\bin\debug folder
8. Click Save
9. In the Solution Explorer, double-click graduates.bmp to make sure it is displayed
10. In the Properties Window, click Width and type 16
11. Click Height and type 16
12. Design the bitmap as follows:

13. In the Solution Explorer, right-click the Debug folder -> Add -> New Item...
14. In the Templates list, make sure Bitmap File is selected.
Set the Name to undergraduates and click Add
15. In the Properties window, click Width and type 16
16. Click Height and type 16
17. Design the bitmap as follows:

18. In the Solution Explorer, right-click the Debug folder -> Add -> New Item...
19. In the Templates list, make sure Bitmap File is selected.
Set the Name to certificates and click Add
20. In the Properties window, click Width and type 16
21. Click Height and type 16
22. Design the bitmap as follows:

23. Display the form


24. Right-click the form and click View Code
25. Declare three variables as follows:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace SchoolEnrolment2
{
public partial class Form1 : Form
{
float Graduates;
float Undergraduates;
float Certificates;

public Form1()
{
InitializeComponent();
}
}
}

26. Return to the form and click an unoccupied area of its body. In the Properties window, click the E
27. Double-click the Paint field and implement the event as follows:

private void Form1_Paint(object sender, PaintEventArgs e)


{
Bitmap bmpGraduates = new Bitmap("graduates.bmp");
TextureBrush brushGraduates = new TextureBrush(bmpGraduates);
Bitmap bmpUndergraduates = new Bitmap("undergraduates.bmp");
TextureBrush brushUndergraduates = new
TextureBrush(bmpUndergraduates);
Bitmap bmpCertificates = new Bitmap("certificates.bmp");
TextureBrush brushCertificates = new TextureBrush(bmpCertificates);
pbxChart.CreateGraphics().FillPie(brushGraduates,
0.0F,
0.0F,
260.0F,
200.0F, 0.0F, Graduates);

pbxChart.CreateGraphics().FillPie(brushUndergraduates,
0.0F,
0.0F,
260.0F,
200.0F, Graduates,
Undergraduates);

pbxChart.CreateGraphics().FillPie(brushCertificates,
0.0F,
0.0F,
260.0F,
200.0F, Graduates +
Undergraduates,
Certificates);

e.Graphics.FillRectangle(brushGraduates,
new Rectangle(lblGraduates.Left,
lblGraduates.Top + 18,
btnClose.Width,
20));

e.Graphics.DrawRectangle(new Pen(Color.Black),
new Rectangle(lblGraduates.Left - 1,
lblGraduates.Top + 18,
btnClose.Width,
20));

e.Graphics.FillRectangle(brushUndergraduates,
new Rectangle(btnClose.Left,
lblUndergraduates.Top + 18,
btnClose.Width,
20));

e.Graphics.DrawRectangle(new Pen(Color.Black),
new Rectangle(btnClose.Left - 1,
lblUndergraduates.Top + 18,
btnClose.Width + 1,
20));

e.Graphics.FillRectangle(brushCertificates,
new Rectangle(btnClose.Left,
lblCertificates.Top + 18,
btnClose.Width,
20));

e.Graphics.DrawRectangle(new Pen(Color.Black),
new Rectangle(btnClose.Left - 1,
lblCertificates.Top + 18,
btnClose.Width + 1,
20));
pbxChart.CreateGraphics().DrawPie(new Pen(Color.Blue),
0.0F,
0.0F,
260.0F,
200.0F, 0.0F, Graduates);
pbxChart.CreateGraphics().DrawPie(new Pen(Color.Red),
0.0F,
0.0F,
260.0F,
200.0F, Graduates, Undergraduates);
pbxChart.CreateGraphics().DrawPie(new Pen(Color.Green),
0.0F,
0.0F,
260.0F,
200.0F, Graduates + Undergraduates,
Certificates);

pbxChart.CreateGraphics().DrawEllipse(new Pen(Color.Red,
2),
new Rectangle(0,
0,
260,
200));
}
28. Return to the form and click the picture box
29. In the Events section of the Properties window, double-click Paint and implement its event as foll

private void pbxChart_Paint(object sender, PaintEventArgs e)


{
Invalidate();
}
30. Return to the form and double-click the Create Chart button
31. Implement the event as follows:

private void btnCreateChart_Click(object sender, EventArgs e)


{
float grad = 0.00F,
under = 0.00F,
cert = 0.00F,
total = 0.00F;
float percentGraduates = 0.00F,
percentUndergraduates = 0.00F,
percentCertificates = 0.00F;

try
{
grad = float.Parse(txtGraduates.Text);
}
catch (FormatException)
{
MessageBox.Show("Invalid Value");
}
try
{
under = float.Parse(txtUndergraduates.Text);
}
catch (FormatException)
{
MessageBox.Show("Invalid Value");
}

try
{
cert = float.Parse(txtCertificates.Text);
}
catch (FormatException)
{
MessageBox.Show("Invalid Value");
}

total = grad + under + cert;


percentGraduates = (grad / total) * 100;
percentUndergraduates = (under / total) * 100;
percentCertificates = (cert / total) * 100;

Graduates = (360 * percentGraduates) / 100;


Undergraduates = (360 * percentUndergraduates) /
100;
Certificates = (360 * percentCertificates) / 100;

pbxChart.Invalidate();
}
32. Return to the form and double-click the Close button
33. Implement its event as follows:

private void btnClose_Click(object sender, EventArgs


e)
{
Close();
}

34. Execute the application and test the form


35. After using it, close the form

File concept:

Watts A Loan: Loan Preparation


Introduction
Imagine you are asked to create an application for a company that is in the
business of lending money, including personal loans (cash loan), car loans,
furniture loans, music instrument loans, etc. One of the actions you would
take consists of creating a form that an employee can use to prepare a loan
presented to a customer. This is the type of example application we will
create.

To implement our application, we will use the Visual Basic library to


calculate the monthly payment that will be applied to the loan. This will be a
file-based application. For this reason, we will create a file to store the
information related to a loan.

Practical Learning: Creating the Application


1. Start Microsoft Visual C# Professional or Microsoft Visual C# 2005 Express Edition
2. To create a new application, on the main menu, click File -> New -> Project...
3. In the Templates list, click Windows Application
4. Set the name to WattsALoan2 and click OK
5. In the Solution Explorer, right-click Form1.cs and click Rename
6. Type LoanPreparation.cs and press Enter
7. To create a new form, on the main menu, click Project -> Add Windows Form...
8. In the Templates list, make sure Windows Form is selected.
Set the Name to NewEmployee and click Add
9. Design the form as follows:
Control Text Name
Label Employee #:
TextBox txtEmployeeNumber
Label Employee Name:
TextBox txtEmployeeName
Button Create btnCreate
Button Close btnClose

10. Double-click the Close button and change the file as follows:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace WattsALoan2b
{
public partial class NewEmployee : Form
{
public NewEmployee()
{
InitializeComponent();
}

private void btnClose_Click(object sender, EventArgs e)


{
Close();
}
}
}
11. Return to the NewEmployee form and double-click its Create button
12. Implement its Click event as follows:

private void btnCreate_Click(object sender, EventArgs e)


{
string strFilename = @"C:\Watts A Loan\Employees.wal";
FileInfo fiEmployees = new FileInfo(strFilename);
StreamWriter stwEmployees = null;

// Normally, we should have the file already but just in


case...
if (!fiEmployees.Exists)
stwEmployees = fiEmployees.CreateText();
else // If the file exists already, then we will only add
to it
stwEmployees = fiEmployees.AppendText();

try
{
stwEmployees.WriteLine(txtEmployeeNumber.Text);
stwEmployees.WriteLine(txtEmployeeName.Text);
}
finally
{
stwEmployees.Close();
}

txtEmployeeNumber.Text = "";
txtEmployeeName.Text = "";
txtEmployeeNumber.Focus();
}
13. To be able to use the Visual Basic library, in the Solution Explorer, right-click References and clic
14. In the .NET property page, click Microsoft.VisualBasic

15. Click OK
16. Display the LoanPreparation form
17. In the Common Controls section of the Toolbox, click ToolTip and click the form
18. Design the form as follows:
Control Name Text ToolTip on toolTip1
If this is a new loan,
enter a new account
number and the
Label
name of the
customer who is
requesting the loan
To open a previously
prepared loan, enter
Label
its account number
and press Tab
Label Acnt #:
Label Customer Name:
Label Customer:
Account number of the customer
TextBox txtAccountNumber
requesting the loan
Name of the customer requesting the
TextBox txtCustomerName
loan
Label Empl #:
Label Employee Name:
Label Prepared By:
Employee number of the clerk
TextBox txtEmployeeNumber
preparing the loan
TextBox txtEmployeeName Name of the clerk preparing the loan
Used to add a new employee to the
Button btnNewEmployee
company
Used to create an account for a new
Button btnNewCustomer
customer
Label Loan Amount:
Amount of loan the customer is
TextBox txtLoanAmount
requesting
Label Interest Rate:
TextBox txtInterestRate Annual percentage rate of the loan
Label %
Label Periods
The number of months the loan is
TextBox txtPeriods
supposed to last
Used to calculate the monthly
Button btnCalculate Calculate
payment
Label Monthly Payment:
The minimum amount the customer
TextBox txtMonthlyPayment
should pay every month
Button btnClose Close Used to close the form

19. Double-click the Calculate button and implement its event as follows:

private void btnCalculate_Click(object sender, EventArgs e)


{
double LoanAmount = 0.00D, MonthlyPayment = 0.00D;
double InterestRate = 0.00D, Periods = 0.00D;

try
{
LoanAmount = double.Parse(txtLoanAmount.Text);
}
catch (FormatException)
{
MessageBox.Show("Invalid Loan Amount");
}

try
{
InterestRate = double.Parse(txtInterestRate.Text);
}
catch (FormatException)
{
MessageBox.Show("Invalid Interest Rate");
}

try
{
Periods = double.Parse(txtPeriods.Text);
}
catch (FormatException)
{
MessageBox.Show("Invalid Periods Value");
}

try
{
MonthlyPayment =
Microsoft.VisualBasic.Financial.Pmt(
InterestRate / 12 / 100,
Periods,
-LoanAmount,
0,
Microsoft.VisualBasic.DueDate.BegOfPeriod);
txtMonthlyPayment.Text =
MonthlyPayment.ToString("F");
}
catch (FormatException)
{
MessageBox.Show("Invalid Periods Value");
}
}
20. Return to the form and double-click the Close button to implement its event as follows:

private void btnClose_Click(object sender, EventArgs e)


{
Close();
}

21. Scroll up completely and, under the other using lines, type using System.IO;
22. Access the LoanPresentation form
23. Double-click the New button on the form and implement the event as follows:

private void btnNewEmployee_Click(object sender, EventArgs e)


{
NewEmployee frmNewEmployee = new NewEmployee();

frmNewEmployee.ShowDialog();
}
24. Return to the form
25. On the LoanPreparation form, double-click an unoccupied area of its body
26. Implement its Load event as follows:

private void LoanPresentation_Load(object sender, EventArgs e)


{
string strDirectory = @"C:\Watts A Loan";

if (!Directory.Exists(strDirectory))
Directory.CreateDirectory(strDirectory);

string strFilename = strDirectory + @"\Employees.wal";

FileInfo fiEmployees = new FileInfo(strFilename);

// If the employees file was not created already,


// then create it
if (!fiEmployees.Exists)
{
StreamWriter stwEmployees = fiEmployees.CreateText();
// And create a John Doe employee
try
{
stwEmployees.WriteLine("00-000");
stwEmployees.WriteLine("John Doe");
}
finally
{
stwEmployees.Close();
}
}
}
27. Return to the LoanPreparation form
28. In the combo box on top of the Properties window, select txtAccountNumber
29. In the Events section, double-click Leave and implement the event as follows:

private void txtAccountNumber_Leave(object sender, EventArgs e)


{
string strPath = @"C:\Watts A Loan";

DirectoryInfo diLoans = new DirectoryInfo(strPath);


FileInfo[] aryLoans = diLoans.GetFiles("*",
SearchOption.AllDirectories);

string strFilename = txtAccountNumber.Text + ".wal";


string strFullname = strPath + "none.wal";
bool found = false;

foreach (FileInfo fle in aryLoans)


{
if (fle.Name == strFilename)
{
found = true;
strFullname = fle.FullName;
}
}

if (found == true)
{
FileStream stmLoans =
File.Open(strFullname,
FileMode.Open,
FileAccess.Read);
BinaryReader bnrLoans = new BinaryReader(stmLoans);

txtAccountNumber.Text = bnrLoans.ReadString();
txtCustomerName.Text = bnrLoans.ReadString();
txtEmployeeNumber.Text = bnrLoans.ReadString();
txtEmployeeName.Text = bnrLoans.ReadString();
txtLoanAmount.Text = bnrLoans.ReadString();
txtInterestRate.Text = bnrLoans.ReadString();
txtPeriods.Text = bnrLoans.ReadString();
txtMonthlyPayment.Text = bnrLoans.ReadString();
bnrLoans.Close();
stmLoans.Close();
}
}
30. In the combo box on top of the Properties window, select txtEmployeeNumber
31. On the Properties window, click the Events button and double-click Leave
32. Implement the event as follows:

private void txtEmployeeNumber_Leave(object sender, EventArgs e)


{
string strFilename = @"C:\Watts A Loan\Employees.wal";
FileInfo fiEmployees = new FileInfo(strFilename);

if (fiEmployees.Exists)
{
if (txtEmployeeNumber.Text == "")
{
txtEmployeeName.Text = "";
return;
}
else
{
StreamReader strEmployees = fiEmployees.OpenText();
string strEmployeeNumber, strEmployeeName;
bool found = false;

try
{
while( (strEmployeeNumber = strEmployees.ReadLine()) !=
null )
{
if (strEmployeeNumber == txtEmployeeNumber.Text)
{
strEmployeeName = strEmployees.ReadLine();
txtEmployeeName.Text = strEmployeeName;
found = true;
}
}

// When the application has finished checking the file


// if there was no employee with that number,
// let the user know
if (found == false)
{
MessageBox.Show("No employee with that number was
found");
txtEmployeeName.Text = "";
txtEmployeeNumber.Focus();
}
}
finally
{
strEmployees.Close();
}
}
}
}
33. Return to the form and double-click the Save button
34. Implement the event as follows:

private void btnSave_Click(object sender, EventArgs e)


{
string strPath = @"C:\Watts A Loan\" + txtAccountNumber.Text +
".wal";

FileStream stmLoan = File.Create(strPath);


BinaryWriter bnwLoan = new BinaryWriter(stmLoan);

bnwLoan.Write(txtAccountNumber.Text);
bnwLoan.Write(txtCustomerName.Text);
bnwLoan.Write(txtEmployeeNumber.Text);
bnwLoan.Write(txtEmployeeName.Text);
bnwLoan.Write(txtLoanAmount.Text);
bnwLoan.Write(txtInterestRate.Text);
bnwLoan.Write(txtPeriods.Text);
bnwLoan.Write(txtMonthlyPayment.Text);

txtAccountNumber.Text = "";
txtCustomerName.Text = "";
txtEmployeeNumber.Text = "";
txtEmployeeName.Text = "";
txtLoanAmount.Text = "";
txtInterestRate.Text = "";
txtPeriods.Text = "";
txtMonthlyPayment.Text = "";

txtAccountNumber.Focus();

bnwLoan.Close();
stmLoan.Close();
}
35. Execute the application to test it
36. First create a few employees as follows:

Employee # Employee Name


42-806 Patricia Katts
75-148 Helene Mukoko
36-222 Frank Leandro
42-808 Gertrude Monay

37. Process a few loans


38. Close the application

Pizza

Danilo Pizza
Creating the Application
This application is used to process orders for a pizza business. It will allow us to view examples
of validating radio buttons and check boxes

Prerequisites:

• Dialog Boxes
• Group Box
• Radio Buttons
• Check Boxes
• Labels
• Text Boxes

This is a classic application that is created from a dialog box.

Practical Learning: Starting the Exercise


1. Start Microsoft Visual C# and create a new Windows Application named Danilo Pizza
2. Design the form as follows:
Control Text Name Additional Properties
GroupBox Pizza Size
RadioButton Small rdoSmall
TextBox 8.95 txtSmall AlignText: Right
RadioButton Medium rdoMedium Checked: True
TextBox 10.75 txtMedium AlignText: Right
RadioButton Large rdoLarge
TextBox 12.95 txtLarge AlignText: Right
GroupBox Side Orders
Label Qty
Label Unit Price
Label Sub Total
Label Bread Sticks
TextBox 0 txtQtyBread AlignText: Right
TextBox 3.25 txtPriceBread AlignText: Right
TextBox 0.00 txtTotalBread AlignText: Right
Label Buffalo Wings
TextBox 0 txtQtyWings AlignText: Right
TextBox 2.15 txtPriceWings AlignText: Right
TextBox 0.00 txtTotalWings AlignText: Right
GroupBox Toppings
CheckBox Pepperoni chkPepperoni CheckAlign: MiddleRight
CheckBox Sausage chkSausage CheckAlign: MiddleRight
CheckBox Extra Cheese chkExtraCheese CheckAlign: MiddleRight
CheckBox Olives chkOlives CheckAlign: MiddleRight
CheckBox Onions chkOnions CheckAlign: MiddleRight
Label Each Topping
TextBox 0.45 txtEachTopping AlignText: Right
GroupBox Drinks
Label Qty
Label Unit Price
Label Sub Total
Label Soda Can
TextBox 0 txtQtyCan AlignText: Right
TextBox 1.45 txtPriceCan AlignText: Right
TextBox 0.00 txtTotalCan AlignText: Right
Label Soda 20 Oz.
TextBox 0 txtQtySoda20 AlignText: Right
TextBox 1.45 txtPriceSoda20 AlignText: Right
TextBox 0.00 txtTotalSoda20 AlignText: Right
Label Soda 2L Bottle
TextBox 0 txtQtySoda2L AlignText: Right
TextBox 1.45 txtPriceSoda2L AlignText: Right
TextBox 0.00 txtTotalSoda2L AlignText: Right
Label Orange Juice
TextBox 0 txtQtyOJ AlignText: Right
TextBox 2.25 txtPriceOJ AlignText: Right
TextBox 0.00 txtTotalOJ AlignText: Right
Label Water
TextBox 0 txtQtyWater AlignText: Right
TextBox 1.25 txtPriceWater AlignText: Right
TextBox 0.00 txtTotalWater AlignText: Right
Button Close btnClose
Label Total Price
Text Box 0.00 txtTotalPrice AlignRight: Right

3. Save everything

Coding the Application


1. In Class View, expand DaniloPizza and expand {} DaniloPizza
2. Right-click Form1 -> Add -> Add Method...
3. Accept the Return Type as void
4. Set the name of the method as CalculatePrice
5. Click Finish and implement the function as follows:

public void CalculatePrice()


{
double PriceSize = 0.00;
double PriceEachTopping, BWings, Bread,
SodaCan, Soda20, Soda2L, OJ, Water, PriceToppings,
TotalOrder;
int Pepperoni, Sausage, ExtraCheese, Onions, Olives;

// Get the price of pizza depending on the selected size


if( rdoSmall.Checked == true )
PriceSize = double.Parse(txtSmall.Text);
if( rdoMedium.Checked == true )
PriceSize = double.Parse(txtMedium.Text);
if( rdoLarge.Checked == true )
PriceSize = double.Parse(txtLarge.Text);

// Get the price of a topping if it was selected


if( chkPepperoni.Checked == true )
Pepperoni = 1;
else
Pepperoni = 0;

if( chkSausage.Checked == true )


Sausage = 1;
else
Sausage = 0;

if( chkExtraCheese.Checked == true )


ExtraCheese = 1;
else
ExtraCheese = 0;

if( chkOnions.Checked == true )


Onions = 1;
else
Onions = 0;

if( chkOlives.Checked == true )


Olives = 1;
else
Olives = 0;

PriceEachTopping = double.Parse(txtEachTopping.Text);
PriceToppings = (Pepperoni + Sausage + ExtraCheese + Onions + Olives) *
PriceEachTopping;

// Calculate the price of the side dishes


// depending on the quantity entered
BWings = double.Parse(txtTotalWings.Text);
Bread = double.Parse(txtTotalBread.Text);

// Calculate the price of the drink(s)


SodaCan = double.Parse(txtTotalCan.Text);
Soda20 = double.Parse(txtTotalSoda20.Text);
Soda2L = double.Parse(txtTotalSoda2L.Text);
OJ = double.Parse(txtTotalOJ.Text);
Water = double.Parse(txtTotalWater.Text);

TotalOrder = PriceSize + PriceToppings + BWings + Bread +


SodaCan + Soda20 + Soda2L + OJ + Water;
txtTotalPrice.Text = TotalOrder.ToString("C");
}
6. On the form double-click each radio button and each check box
7. In their implementation, simply call the CalculatePrice() function:

private void rdoSmall_CheckedChanged(object sender, System.EventArgs


e)
{
CalculatePrice();
}

private void rdoMedium_CheckedChanged(object sender,


System.EventArgs e)
{
CalculatePrice();
}

private void rdoLarge_CheckedChanged(object sender,


System.EventArgs e)
{
CalculatePrice();
}

private void chkPepperoni_CheckedChanged(object


sender, System.EventArgs e)
{
CalculatePrice();
}

private void chkSausage_CheckedChanged(object sender,


System.EventArgs e)
{
CalculatePrice();
}

private void chkExtraCheese_CheckedChanged(object


sender, System.EventArgs e)
{
CalculatePrice();
}

private void chkOlives_CheckedChanged(object sender,


System.EventArgs e)
{
CalculatePrice();
}
private void chkOnions_CheckedChanged(object sender,
System.EventArgs e)
{
CalculatePrice();
}
8. Test the application
9. On the form, click the Qty text box corresponding to the Bread Sticks

10. In the Properties window, click the Events button and, in the list of events, double-click Leave
11. In the same way, initiate the Leave of the Qty text box of the Buffalo Wings and the drinks
12. Implement the events as follows:

private void txtQtyBread_Leave(object sender, System.EventArgs e)


{
int Qty;
double Price, Total;

if( txtQtyBread.Text == "" )


Qty = 0;
else
Qty = Int32.Parse(txtQtyBread.Text);

Price = double.Parse(txtPriceBread.Text);

Total = Qty * Price;


txtTotalBread.Text = Total.ToString("F");

CalculatePrice();
}

private void txtQtyWings_Leave(object sender,


System.EventArgs e)
{
int Qty;
double Price, Total;

if( txtQtyWings.Text == "" )


Qty = 0;
else
Qty = Int32.Parse(txtQtyWings.Text);

Price = double.Parse(txtPriceWings.Text);

Total = Qty * Price;


txtTotalWings.Text = Total.ToString("F");

CalculatePrice();
}

private void txtQtyCan_Leave(object sender,


System.EventArgs e)
{
int Qty;
double Price, Total;

if( txtQtyCan.Text == "" )


Qty = 0;
else
Qty = Int32.Parse(txtQtyCan.Text);

Price = double.Parse(txtPriceCan.Text);

Total = Qty * Price;


txtTotalCan.Text = Total.ToString("F");

CalculatePrice();
}

private void txtQtySoda20_Leave(object sender,


System.EventArgs e)
{
int Qty;
double Price, Total;

if( txtQtySoda20.Text == "" )


Qty = 0;
else
Qty = Int32.Parse(txtQtySoda20.Text);

Price = double.Parse(txtPriceSoda20.Text);

Total = Qty * Price;


txtTotalSoda20.Text = Total.ToString("F");

CalculatePrice();
}

private void txtQtySoda2L_Leave(object sender,


System.EventArgs e)
{
int Qty;
double Price, Total;

if( txtQtySoda2L.Text == "" )


Qty = 0;
else
Qty = Int32.Parse(txtQtySoda2L.Text);

Price = double.Parse(txtPriceSoda2L.Text);

Total = Qty * Price;


txtTotalSoda2L.Text = Total.ToString("F");

CalculatePrice();
}

private void txtQtyOJ_Leave(object sender,


System.EventArgs e)
{
int Qty;
double Price, Total;

if( txtQtyOJ.Text == "" )


Qty = 0;
else
Qty = Int32.Parse(txtQtyOJ.Text);

Price = double.Parse(txtPriceOJ.Text);

Total = Qty * Price;


txtTotalOJ.Text = Total.ToString("F");

CalculatePrice();
}

private void txtQtyWater_Leave(object sender,


System.EventArgs e)
{
int Qty;
double Price, Total;

if( txtQtyWater.Text == "" )


Qty = 0;
else
Qty = Int32.Parse(txtQtyWater.Text);

Price = double.Parse(txtPriceWater.Text);

Total = Qty * Price;


txtTotalWater.Text = Total.ToString("F");

CalculatePrice();
}
13. On the form, double-click the Close button and implement its Click event as follows:

private void button1_Click(object sender, System.EventArgs e)


{
Close();
}
14. Test the application

Example Application:
The HTML Body Tag Formatter
Description
If you have ever created web pages using HTML, you are probably familiar
with that language's various tags and you may know that a tag can contain
attributes. An example of a tag would be <body> and inside of the tag, you
can create the attributes you want.

This application shows an example of visually creating the attributes of the


HTML's body tag, mainly the colors.

Windows Controls:

• Label
• Panel
• Button
• Text Box
• Group Box
• Scroll Bar

Practical Learning: Creating the Application


1. Start a new Windows Application named HTMLBodyTag1
2. Design the form as follows:

Control Name Text Other Properties

GroupBox Body Attributes

RadioButton rdoBackground Background Checked: True

TextBox txtBackground #000000

RadioButton rdoText Text

TextBox txtText #0000FF

RadioButton rdoLink Link

TextBox txtLink #FF0000

RadioButton rdoActiveLink Active Link

TextBox txtActiveLink #008000

RadioButton rdoVisitedLink Visited Link


TextBox txtVisitedLink #800000

BackColor: White
Panel pnlPreview
BorderStyle: Fixed3D

VScrollBar scrRed

VScrollBar scrGreen

VScrollBar scrBlue

Label R

Label G

Label B

BackColor: White
Panel pnlBody
BorderStyle: Fixed3D
BorderStyle: None
TextBox txtTextPreview Body tag formatter and colorizer ForeColor: Blue
TextAlign: Center
BorderStyle: None
TextBox txtLinkPreview Sample text as link ForeColor: Red
TextAlign: Center
BorderStyle: None
TextBox txtALinkPreview Current active link ForeColor: Green
TextAlign: Center
BorderStyle: None
TextBox txtVLinkPreview This link has been visited ForeColor: Maroon
TextAlign: Center

GroupBox Color's Values

Label Red:

TextBox txtRed 0

Label Green:

TextBox txtGreen 0

Label Blue:

TextBox txtBlue 0

Button btnCopy Copy

Button btnClose Close

<body bgcolor="#FFFFFF" text="#0000FF" link="#FF0000"


TextBox txtResult
alink="#008000" vlink="#800000">
3. Save all
4. On the form, click one of the scroll bars
5. Press and hold Ctrl
6. Click the other two scroll bars and release Ctrl
7. In the Properties window, click Maximum, type 255, and press Enter
8. Click an unoccupied area of the form to make sure no control is selected
9. On the form, click one of the scroll bars
10. Press and hold Ctrl
11. Click the other two scroll bars and release Ctrl
12. In the Properties window, click LargeChange, type 1, and press Enter

13. Right-click the form and click View Code


14. Change the file as follows:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace HTMLBodyTag1
{
public partial class Form1 : Form
{
private string HexBG, HexText, HexLink, HexALink, HexVLink;

public Form1()
{
InitializeComponent();
}

internal void ApplyColor()


{
// Retrieve the current hexadecimal
// colors from their Edit controls
HexBG = txtBackground.Text;
HexText = txtText.Text;
HexLink = txtLink.Text;
HexALink = txtActiveLink.Text;
HexVLink = txtVisitedLink.Text;

// Get the integral position of each ScrollBar control


string strRed = Convert.ToString(255 - scrRed.Value);
string strGreen = Convert.ToString(255 - scrGreen.Value);
string strBlue = Convert.ToString(255 - scrBlue.Value);

// Display the position of each ScrollBar


// in its corresponding Edit control
txtRed.Text = strRed;
txtGreen.Text = strGreen;
txtBlue.Text = strBlue;

// Change the color of the Preview panel


// according to the values of the ScrollBar positions
pnlPreview.BackColor = Color.FromArgb(255 - scrRed.Value,
255 -
scrGreen.Value,
255 -
scrBlue.Value);

string FmtRed = (255 - scrRed.Value).ToString("X");


if (FmtRed.Length == 1)
FmtRed = String.Concat("0", FmtRed);

string FmtGreen = (255 - scrGreen.Value).ToString("X");


if (FmtGreen.Length == 1)
FmtGreen = String.Concat("0", FmtGreen);

string FmtBlue = (255 - scrBlue.Value).ToString("X");


if (FmtBlue.Length == 1)
FmtBlue = String.Concat("0", FmtBlue);

// Get the position of each ScrollBar control


// Create a hexadecimal color starting with #
// And display the color in the appropriate Edit control
if (rdoBackground.Checked == true)
{
string BG = "#";
BG = String.Concat(BG, FmtRed);
BG = String.Concat(BG, FmtGreen);
BG = String.Concat(BG, FmtBlue);

txtBackground.Text = BG;
pnlBody.BackColor = pnlPreview.BackColor;
txtTextPreview.BackColor = pnlPreview.BackColor;
txtLinkPreview.BackColor = pnlPreview.BackColor;
txtALinkPreview.BackColor = pnlPreview.BackColor;
txtVLinkPreview.BackColor = pnlPreview.BackColor;

HexBG = txtBackground.Text;
}
else if (rdoText.Checked == true)
{
string Txt = "#";
Txt = String.Concat(Txt, FmtRed);
Txt = String.Concat(Txt, FmtGreen);
Txt = String.Concat(Txt, FmtBlue);

txtText.Text = Txt;
txtTextPreview.ForeColor =
Color.FromArgb(255 - scrRed.Value,
255 - scrGreen.Value,
255 - scrBlue.Value);
HexText = txtText.Text;
}
else if (rdoLink.Checked == true)
{
string TL = "#";
TL = String.Concat(TL, FmtRed);
TL = String.Concat(TL, FmtGreen);
TL = String.Concat(TL, FmtBlue);

txtLink.Text = TL;
txtLinkPreview.ForeColor =
Color.FromArgb(255 - scrRed.Value,
255 - scrGreen.Value,
255 - scrBlue.Value);

HexLink = txtLink.Text;
}
else if (rdoActiveLink.Checked == true)
{
string AL = "#";
AL = String.Concat(AL, FmtRed);
AL = String.Concat(AL, FmtGreen);
AL = String.Concat(AL, FmtBlue);

txtActiveLink.Text = AL;
txtALinkPreview.ForeColor =
Color.FromArgb(255 - scrRed.Value,
255 - scrGreen.Value,
255 - scrBlue.Value);

HexALink = txtActiveLink.Text;
}
else if (rdoVisitedLink.Checked == true)
{
string VL = "#";
VL = String.Concat(VL, FmtRed);
VL = String.Concat(VL, FmtGreen);
VL = String.Concat(VL, FmtBlue);

txtVisitedLink.Text = VL;
txtVLinkPreview.ForeColor =
Color.FromArgb(255 - scrRed.Value,
255 - scrGreen.Value,
255 - scrBlue.Value);

HexVLink = txtVisitedLink.Text;
}

// Update the contents of the bottom text box


string BD = "<body bgcolor=\"";
BD = String.Concat(BD, HexBG);
BD = String.Concat(BD, "\" text=\"");
BD = String.Concat(BD, HexText);
BD = String.Concat(BD, "\" link=\"");
BD = String.Concat(BD, HexLink);
BD = String.Concat(BD, "\" alink=\"");
BD = String.Concat(BD, HexALink);
BD = String.Concat(BD, "\" vlink=\"");
BD = String.Concat(BD, HexVLink);
BD = String.Concat(BD, "\">");

txtResult.Text = BD;
}
}
}
15. Return to the form and double-click the left scroll bar
16. Implement its event as follows:

private void scrRed_Scroll(object sender, ScrollEventArgs e)


{
ApplyColor();
}
17. Return to the form and double-click the middle scroll bar
18. Implement its event as follows:

private void scrGreen_Scroll(object sender, ScrollEventArgs e)


{
ApplyColor();
}
19. Return to the form and double-click the right scroll bar
20. Implement its event as follows:

private void scrBlue_Scroll(object sender, ScrollEventArgs e)


{
ApplyColor();
}
21. Execute the application to test the form
22. Close the form and return to your programming environment
23. When the user clicks a radio button from the Body Attributes group box, we need to display its co
panel. When a particular button is clicked, we will retrieve the color of its font from the Body text
color into red, green, and blue values, and then use those values to automatically update the scr
boxes. While we are at it, we also need to update the corresponding text box in the Body Attribut
this functionality will be used by all radio buttons in the group, we will use a global function to wh
two variables.
When the user clicks a particular radio button, that button is represented by a text box in the low
section. We need to get the color of that edit box and pass it to our function. Since the clicked ra
corresponding text box in the Body Attributes group box, we need to change/update that value w
value of the first argument. Therefore, we will pass a string argument to our function.
In the Code Editor, just after the closing curly bracket of the scrBlue_Scroll event, create the follo

internal void ClickOption(System.Drawing.Color Clr, String


Result)
{
// These variables will hold the red, green, and blue
// values of the passed color
int red, green, blue;

// Colorize the Preview panel with the passed color


pnlPreview.BackColor = Clr;

// Get the red value of the color of the Preview panel


red = 255 - pnlPreview.BackColor.R;
// Get the green value of the color of the Preview panel
green = 255 - pnlPreview.BackColor.G;
// Get the blue value of the color of the Preview panel
blue = 255 - pnlPreview.BackColor.B;

// Now that we have the red, green, and blue values of


the color,
// Update the scroll bars with the new values
scrRed.Value = red;
scrGreen.Value = green;
scrBlue.Value = blue;

// Update the red, green, and blue values


// of the Numeric Values group box
txtRed.Text = red.ToString();
txtGreen.Text = green.ToString();
txtBlue.Text = blue.ToString();
// Update the string that was passed using
// the retrieved red, green, and blue values
Result = String.Concat(Result, "#");
Result = String.Concat(Result, red.ToString("X"));
Result = String.Concat(Result, green.ToString("X"));
Result = String.Concat(Result, blue.ToString("X"));
}
24. Return to the form
25. Double-click the Background radio button and implement its event as follows:

private void rdoBackground_CheckedChanged(object sender, EventArgs e)


{
// If the user clicks Background radio button
// set color of the panel to that of the radio button
Color BGColor = pnlBody.BackColor;

pnlBody.BackColor = BGColor;

// Call the ClickOption() method to calculate


// the hexadecimal value of the color
ClickOption(pnlBody.BackColor, txtBackground.Text);
HexBG = txtBackground.Text;
}
26. Return to the form
27. Double-click the Text radio button and implement its event as follows:

private void rdoText_CheckedChanged(object sender, EventArgs e)


{
Color BGColor = pnlBody.BackColor;
txtTextPreview.BackColor = BGColor;

ClickOption(txtTextPreview.ForeColor, txtText.Text);
HexText = txtText.Text;
}
28. Return to the form
29. Double-click the Link radio button and implement its event as follows:

private void rdoLink_CheckedChanged(object sender, EventArgs e)


{
Color BGColor = pnlBody.BackColor;
txtLinkPreview.BackColor = BGColor;

ClickOption(txtLinkPreview.ForeColor, txtLink.Text);
HexLink = txtLink.Text;
}
30. Return to the form
31. Double-click the Active Link radio button and implement its event as follows:

private void rdoActiveLink_CheckedChanged(object sender, EventArgs e)


{
Color BGColor = pnlBody.BackColor;
txtALinkPreview.BackColor = BGColor;

ClickOption(txtALinkPreview.ForeColor,
txtActiveLink.Text);
HexALink = txtActiveLink.Text;
}
32. Return to the form
33. Double-click the Visited Link radio button and implement its event as follows:

private void rdoVisitedLink_CheckedChanged(object sender,


EventArgs e)
{
Color BGColor = pnlBody.BackColor;
txtVLinkPreview.BackColor = BGColor;

ClickOption(txtVLinkPreview.ForeColor,
txtVisitedLink.Text);
HexVLink = txtVisitedLink.Text;
}
34. Return to the form
35. Double-click the Copy button and implement it as follows:

private void btnCopy_Click(object sender, EventArgs e)


{
txtResult.SelectAll();
txtResult.Copy();
}
36. Return to the form
37. Double-click the Close button and implement it as follows:

private void btnClose_Click(object sender, EventArgs e)


{
Close();
}

38. Execute the application


39. Close the form

Controls:

Windows Control: The Button


Description
On a typical application, a button is an object that the user clicks to perform
an action. To make this obvious, a button is a control surrounded by thick
borders. Here is an example of a button on a form:

Although a control is usually positioned on a form, there various other control containers that can h
include the toolbar or the status bar, and the other containers we have used so far.

To indicate what it is used for, a button displays some text as its caption. A button can also displa
Another button can display both a string and a picture. When you create a button, you will decide w
and how it should behave.

Practical Learning: Introducing Buttons


1. Start Microsoft Visual C# and create a Windows Application named Algebra2
2. On the main menu, click Project -> Add Class...
3. In the Templates list, make sure Class is selected.
Change the Name to Algebra and click Add
4. Change the file as follows:

using System;

namespace Algebra2
{
public class Algebra
{
public static long Factorial(long x)
{
if (x <= 1)
return 1;
else
return x * Factorial(x - 1);
}

public static long Permutation(long n, long r)


{
if (r == 0)
return 0;
if (n == 0)
return 0;
if ((r >= 0) && (r <= n))
return Factorial(n) / Factorial(n - r);
else
return 0;
}

public static long Combinatorial(long a, long b)


{
if (a <= 1)
return 1;

return Factorial(a) / (Factorial(b) * Factorial(a - b));


}
}
}
5. In the Solution Explorer, right-click Form1.cs and click Rename
6. Type Exercise.cs and press Enter twice (to save and to open the form)
7. Click the body of the form to make sure it is selected.
In the Properties window, change the following characteristics
FormBorderStyle: FixedDialog
Text: Factorial, Permutation, and Combination
Size: 304, 208
StartPosition: CenterScreen
MaximizeBox: False
MinimizeBox: False
8. In the Containers section of the Toolbox, click TabControl and click the form
9. On the form, right-click the right side of tabPage2 and click Add Page
10. Based on what we learned in Lesson 24, design the form as follows:

Control Text Name Additional Properties


HotTrack: True
TabControl tclAlgebra Location: 12, 12
Size: 304, 235
TabPage Factorial tabFactorial
Label Number: Location: 22, 21
TextAlign: Right
TextBox txtNumber Location: 88, 18
Size: 50, 20
Label Result: Location: 22, 56
TextAlign: Right
TextBox txtFactorial Location: 88, 54
Size: 140, 20
Control Text Name Location Size
TabPage Permutation tabPermutation
Label n: 22, 21
TextBox txtPermutationN 88, 18 50, 20
Label r: 22, 56
TextBox txtPermutationR 88, 54 50, 20
Label P(n, r): 22, 92
TextBox txtPermutation 88, 90 140, 20

Control Text Name Location Size


TabPage Combination tabCombination
Label n: 22, 21
TextBox txtCombinationN 88, 18 50, 20
Label r: 22, 56
TextBox txtCombinationR 88, 54 50, 20
Label C(n, r): 22, 92
TextBox txtCombination 88, 90 140, 20

11. Save the form

Creating a Button
To support the buttons of an application, the .NET Framework provides an abstract class named Butto
button of Microsoft Windows is implemented by the Button class. At design time, to add a button t
the Common Controls section of the Toolbox, you can click the Button and click the form or another co

To programmatically create a button, you can declare a variable of type Button and use the new
memory for it. Here is an example:

using System;
using System.Drawing;
using System.Windows.Forms;

public class Exercise : System.Windows.Forms.Form


{
Button btnResume;

public Exercise()
{
InitializeComponent();
}

private void InitializeComponent()


{
btnResume = new Button();
btnResume.Location = new Point(32, 20);

this.Controls.Add(btnResume);
}
}

public class Program


{
static int Main()
{
System.Windows.Forms.Application.Run(new Exercise());
return 0;
}
}
Practical Learning: Creating Buttons
1. In the combo box on top of the Properties window, select tabFactorial
2. From the Common Controls section of the Toolbox, click Button and click on the right side of the

The Characteristics of a Button


The Caption of a Button
For a user, the most important aspects of a button are the message it
displays and the action it performs. The text the button displays allows the
user to know what the button is used for. This is represented by the Text
property. The most popular strings that the buttons display are OK and
Cancel. The OK caption is set for a form or a dialog box that informs the
user of an error, an intermediary situation, or an acknowledgement of an
action that was performed on the dialog that hosts the button. The Cancel
caption is useful on a button whose main parent (the form or the dialog box)
would ask a question or request a follow-up action from the user. Whenever
a dialog box allows the user to dismiss it without continuing the action, you
should provide a button with a Cancel caption.

After adding a button to a form (by design or with code), you can change its caption with code by a
string to the Text property. For example, you can change the caption of a button as follows:

button1.Text = "Let it Go!";

After specifying the Text of a button, by default, it's positioned in the middle center of the button:

The position of the text of a button is controlled through the TextAlign property which
ContentAlignment enumerator. The possible values are:

TopLeft TopCenter TopRight

MiddleLeft MiddleCenter MiddleRight

BottomLeft BottomCenter BottomRight

Here is an example:

public class Exercise : System.Windows.Forms.Form


{
Button btnResume;

public Exercise()
{
InitializeComponent();
}

private void InitializeComponent()


{
btnResume = new Button();
btnResume.Text = "Resume";
btnResume.Location = new Point(32, 20);
btnResume.Size = new System.Drawing.Size(120, 48);
btnResume.TextAlign = ContentAlignment.BottomCenter;

Controls.Add(btnResume);
}
}

Practical Learning: Using the Buttons


1. Access each tab page and add a button to it
2. Add a button to the form and under the tab control
3. Complete the design of the form as follows:

Control Text Name


Button Calculate btnCalcFactorial
Button Close btnClose
Control Text Name
Button Calculate btnCalcPermutation

Control Text Name


Button Calculate btnCalcCombination

4. Access the Factorial tab page and double-click its Calculate button
5. Implement the event as follows:

private void btnCalcFactorial_Click(object sender, EventArgs e)


{
long number = 0;
long result;

try
{
number = long.Parse(txtFactNumber.Text);
result = Algebra.Factorial(number);
txtFactorial.Text = result.ToString();
}
catch (FormatException)
{
MessageBox.Show("Invalid Number");
}
}
6. Return to the form
7. Access the Permutation tab page and double-click its Calculate button
8. Implement the event as follows:

private void btnCalcPermutation_Click(object sender, EventArgs e)


{
long n = 0, r = 0;
long result;

try
{
n = long.Parse(txtPermutationN.Text);
}
catch (FormatException)
{
MessageBox.Show("Invalid Number");
}

try
{
r = long.Parse(txtPermutationR.Text);
result = Algebra.Permutation(n, r);
txtPermutation.Text = result.ToString();
}
catch (FormatException)
{
MessageBox.Show("Invalid Number");
}
}
9. Return to the form
10. Access the Combination tab page and double-click its Calculate button
11. Implement the event as follows:

private void btnCalcCombination_Click(object sender, EventArgs e)


{
long n = 0, r = 0;
long result;

try
{
n = long.Parse(txtCombinationN.Text);
}
catch (FormatException)
{
MessageBox.Show("Invalid Number");
}

try
{
r = long.Parse(txtCombinationR.Text);
result = Algebra.Combinatorial(n, r);
txtCombination.Text = result.ToString();
}
catch (FormatException)
{
MessageBox.Show("Invalid Number");
}
}
12. Return to the form and double-click the Close button
13. Implement the event as follows:

private void btnClose_Click(object sender, EventArgs e)


{
Close();
}
14. Execute the application to test the calculations
15. Close the form and return to your programming environment

The Image on a Button


Besides, or instead, of a caption, a button can display a picture on top. If you want a button to di
should first create, design, or have a picture. Then, in the Properties window, use the Image field t
an icon. You can also programmatically assign an Image object to the Image property. Here is an ex

private void InitializeComponent()


{
btnResume = new Button();
btnResume.Text = "Resume";
btnResume.Location = new Point(32, 20);
btnResume.Size = new System.Drawing.Size(120, 48);
btnResume.Image = Image.FromFile(@"E:\Programs\neutral.gif");

Controls.Add(btnResume);
}

This would produce:

By default, both the caption and the image display ion the middle-center of the button. To make the
the user to see both, you can design a bitmap that has both and assign that bitmap as the im
Alternatively, you can use a separate string and a separate picture. Fortunately, each can have its
already saw how to control the alignment of the caption.

Besides displaying an image, the Button class is equipped with the ImageAlign property that allow
alignment of the image. The ImageAlign property is inherited from the Button
ButtonBase.ImageAlign property is based on the ContentAlignment enumeration that we are a
Here is an example:

private void InitializeComponent()


{
btnResume = new Button();
btnResume.Location = new Point(32, 20);
btnResume.Size = new System.Drawing.Size(120, 48);
btnResume.Text = "Resume";
btnResume.TextAlign = ContentAlignment.BottomCenter;
btnResume.Image = Image.FromFile(@"E:\Programs\neutral.gif");
btnResume.ImageAlign = ContentAlignment.TopCenter;

Controls.Add(btnResume);
}

This would produce:

Instead of using the Image property, you can first create an image list and add some pictures to
ImageList property, assign it to the button. Use the ImageIndex property to specify what picture
on the button.

The Flat Style of a Button


A regular button displays with raised borders as originally set by the operating system. To give your
and behavior, you can use the FlatStyle property. The FlatStyle property is based on an enume
name. It provides 4 values that are:

• Flat: The button appears flat. When the mouse is over it, it becomes highlighted

• Popup: The button appears flat. When the mouse is over it, the borders of the button are

• Standard: The button appears and behave like all regular buttons you have seen

• System: The appearance of the button depends on the operating system

Obviously the most important and the most intuitive event of a button occurs when clicked. Th
EventArgs, which indicates that it doesn't provide nor does it need any formal details about what is
this event, you can double-click the button on the form. To create this event programmatically,
method that would carry its assignment, then increment-add (with the += operator) it to the Click pr
by assigning it the EventHandler constructor.

The Result of a Dialog Box


After the user has used a form or dialog box, to close it, the user would click a button. When the user
find out what button was clicked. Although there are various ways you can get this information, to
Framework provides a convenient mechanism through an enumeration named DialogResult.

When creating a form or a dialog box, after adding a button, in the Properties window, click DialogR
the values:
Except for None, by default, it does not matter what value you select but, you should follow Windows
the right value.

After specifying the returned value of a button, access the properties of the form or dialog box:

• If you had selected OK as the DialogResult value of a button, you should select the name of tha
AcceptButton property of the form
• If you had selected Cancel as the DialogResult value of a button, you should select the name of
CancelButton property of the form

After configuring the DialogResult of the button(s), when the user clicks one of the buttons to clos
box, you can get the value of the Form.ShowDialog() method which returns one of the values o
enumeration.

Checkedlistbox :

Practical Learning: Introducing Checked List Boxes


1. Start a new Windows Application named AltairRealtors1
2. On the main menu, click Project ->Add Class...
3. Set the Name to AvailableProperty and click Add
4. Change the file as follows:

using System;

namespace AltairRealtors1
{
public class AvailableProperty
{
long propNbr;
string propType;
string adrs;
string ct;
string stt;
int zip;
short beds;
float baths;
double mValue;

public long PropertyNumber


{
get { return propNbr; }
set { propNbr = value; }
}

public string PropertyType


{
get { return propType; }
set { propType = value; }
}

public string Address


{
get { return adrs; }
set { adrs = value; }
}

public string City


{
get { return ct; }
set { ct = value; }
}

public string State


{
get { return stt; }
set { stt = value; }
}

public int ZIPCode


{
get { return zip; }
set { zip = value; }
}

public short Bedrooms


{
get { return beds; }
set { beds = value; }
}

public float Bathrooms


{
get { return baths; }
set { baths = value; }
}
public double MarketValue
{
get { return mValue; }
set { mValue = value; }
}

public AvailableProperty()
{
}

public AvailableProperty(long code, string type,


string address, string city,
string state, int zCode,
short bedroom, float bathroom,
double value)
{
propNbr = code ;
propType = type ;
adrs = address ;
ct = city ;
stt = state ;
zip = zCode ;
beds = bedroom ;
baths = bathroom ;
mValue = value;
}
}
}
5. In the Solution Explorer, right-click Form1.cs and click Rename
6. Type RealEstate.cs and press Enter twice
Creating a Checked List Box
To support checked list boxes, the .NET Framework provides the CheckedListBox
class. At design time, to add a checked list box to your application, from the

Common Controls section of the Toolbox, click the CheckedListBox button and
click the form or the container that would host the control. To programmatically
create a checked list box, declare a variable of type CheckedListBox, use the new
operator to allocate memory for it, and add it to the Controls collection of its
parent. Here is an example:

using System;
using System.Drawing;
using System.Windows.Forms;

public class Exercise : System.Windows.Forms.Form


{
CheckedListBox lbxPersonalRelationships;

public Exercise()
{
InitializeComponent();
}
private void InitializeComponent()
{
lbxPersonalRelationships = new CheckedListBox();
lbxPersonalRelationships.Location = new Point(12, 12);

Controls.Add(lbxPersonalRelationships);
}
}

public class Program


{
static int Main()
{
System.Windows.Forms.Application.Run(new Exercise());
return 0;
}
}

This would produce:

Practical Learning: Creating Checked List Boxes


1. Design the form as follows:
Other
Control Text Name
Properties
BorderStyle:
FixedSingle
Font: Times
Label Altair Realtors
New Roman,
21.75pt,
style=Bold

Label Types to Show

CheckedListBox lbxPropertiesTypes

Button Show btnShow

Font:
Garamond,
Label Properties_______
15.75pt,
style=Bold

Label Prop #

Label Address

Label City
Label State

Label ZIP Code

Label Beds

Label Baths

Label Market Value

ListBox lbxPropertyNumbers

ListBox lbxAddresses

ListBox lbxCities

ListBox lbxStates

ListBox lbxZIPCodes

ListBox lbxBedrooms

ListBox lbxBathrooms

ListBox lbxMarketValues

Button Close btnClose

2. Save the form

Introduction
The CheckedListBox class is derived from the ListBox class. This means
that the checked list box possesses all the public (and protected)
characteristics of the list box and its parent the ListControl class. This
control also uses the HorizontalScrollbar and the HorizontalExtent
properties that behave exactly as we reviewed for the list box. It also uses
the SelectionMode property with the same behavior as that of the list
box.

Creating the List of Items


As seen for the list box, the primary aspect of a checked list box is its list of items. At design time,
items of a checked list box, access its Properties window, and click the ellipsis button to open t
Editor. Type each item followed by a carriage return. After creating the list, click OK. To programmat
of items, access the Items property. The list is created from the nested ObjectCollection class t
IList, the ICollection, and the IEnumerable interfaces. This means that the CheckedListBox.Obj
behaves the same as the ListBox.ObjectCollection class. Here is an example:

public class Exercise : System.Windows.Forms.Form


{
CheckedListBox lbxPersonalRelationships;

public Exercise()
{
InitializeComponent();
}

private void InitializeComponent()


{
lbxPersonalRelationships = new CheckedListBox();
lbxPersonalRelationships.Location = new Point(12, 12);

lbxPersonalRelationships.Items.Add("Family Member");
lbxPersonalRelationships.Items.Add("Friend");
lbxPersonalRelationships.Items.Add("Classmate");
lbxPersonalRelationships.Items.Add("Business Partner");
lbxPersonalRelationships.Items.Add("Simple Acquaintance");
lbxPersonalRelationships.Items.Add("Undefined");

Controls.Add(lbxPersonalRelationships);
}
}

This would produce:

Remember that you can also add an array of items by calling the AddRange() and you can inser
Insert() method.

Practical Learning: Creating a List of Items


1. On the form, click the checked list box
2. In the Properties window, click Items and click its ellipsis button
3. In the String Collection Editor, type Single Families and press Enter
4. Type Townhouses and press Enter
5. Type Condominiums and press Enter
6. Type Trailers and click OK
Checking an Item
As mentioned already, the main difference between a list box and a checked list is the presence of
former. When using the control, the user can click one or more check boxes. Here is an example:

After the user has clicked a few check boxes, you may want to find out which ones are checked. T
provides two techniques you can use.

As seen for the list box, each item of the control has an index. When one, a few, or all items have b
that display a check mark), the indices of the checked items are stored in a collection r
CheckedIndices property. This property is based on the nested CheckedIndexCollection c
CheckedIndexCollection class implements the IList, the ICollection, and the IEnumerable interfa

The identifications of the checked items are stored in a collection represented by the CheckedIt
property is based on the nested CheckedItemCollection class. The CheckedItemCollection cl
IList, the ICollection, and the IEnumerable interfaces. This implies that you can use it to get the
items.

When the user has clicked item to put a check mark on it, the control fires the ItemCheck event. Its

private void lbxPropertiesTypes_ItemCheck(object sender, ItemCheckEventArgs e)


{

As you can see, the event is carried by the ItemCheckEventArgs class.

One of the most important operations to perform on a list of selected items is to find out whether
checked. To get this information, the CheckedItemCollection class provides a method named Conta

public bool Contains(object item);

This method takes as argument a value that can identify an item from the checked list box. If the ite
checked, this method returns true. Otherwise, it returns false.

Practical Learning: Using the List of Checked Items


1. Double-click an unoccupied area of the form to generate its Load event
2. Change the file as follows:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace AltairRealtors1
{
public partial class RealEstate : Form
{
AvailableProperty[] properties = new AvailableProperty[15];

public RealEstate()
{
InitializeComponent();
}

private void RealEstate_Load(object sender, EventArgs e)


{
properties[0] = new AvailableProperty();
properties[0].PropertyNumber = 602138;
properties[0].PropertyType = "Single Family";
properties[0].Address = "11604 Aldora Avenue";
properties[0].City = "Baltimore";
properties[0].State = "MD";
properties[0].ZIPCode = 21205;
properties[0].Bedrooms = 5;
properties[0].Bathrooms = 3.5F;
properties[0].MarketValue = 265880;

properties[1] = new AvailableProperty();


properties[1].PropertyNumber = 749562;
properties[1].PropertyType = "Townhouse";
properties[1].Address = "495 Parker House Terrace";
properties[1].City = "Gettysburg";
properties[1].State = "WV";
properties[1].ZIPCode = 26201;
properties[1].Bedrooms = 3;
properties[1].Bathrooms = 2.5F;
properties[1].MarketValue = 225500;

properties[2] = new AvailableProperty();


properties[2].PropertyNumber = 304750;
properties[2].PropertyType = "Condominium";
properties[2].Address = "5900 24th Street NW #812";
properties[2].City = "Washington";
properties[2].State = "DC";
properties[2].ZIPCode = 20008;
properties[2].Bedrooms = 1;
properties[2].Bathrooms = 1.0F;
properties[2].MarketValue = 388665;

properties[3] = new AvailableProperty();


properties[3].PropertyNumber = 682630;
properties[3].PropertyType = "Single Family";
properties[3].Address = "6114 Costinna Avenue";
properties[3].City = "Martinsburg";
properties[3].State = "WV";
properties[3].ZIPCode = 25401;
properties[3].Bedrooms = 4;
properties[3].Bathrooms = 3.5F;
properties[3].MarketValue = 325000;

properties[4] = new AvailableProperty();


properties[4].PropertyNumber = 480750;
properties[4].PropertyType = "Condominium";
properties[4].Address = "10710 Desprello Street #10D";
properties[4].City = "Rockville";
properties[4].State = "MD";
properties[4].ZIPCode = 20856;
properties[4].Bedrooms = 1;
properties[4].Bathrooms = 1.0F;
properties[4].MarketValue = 528445;

properties[5] = new AvailableProperty();


properties[5].PropertyNumber = 209475;
properties[5].PropertyType = "Single Family";
properties[5].Address = "519D Estuardo Way";
properties[5].City = "Silver Spring";
properties[5].State = "MD";
properties[5].ZIPCode = 20906;
properties[5].Bedrooms = 2;
properties[5].Bathrooms = 1.0F;
properties[5].MarketValue = 325995;

properties[6] = new AvailableProperty();


properties[6].PropertyNumber = 304185;
properties[6].PropertyType = "Townhouse";
properties[6].Address = "10116 Lottsford Drive";
properties[6].City = "Takoma Park";
properties[6].State = "MD";
properties[6].ZIPCode = 20910;
properties[6].Bedrooms = 4;
properties[6].Bathrooms = 3.5F;
properties[6].MarketValue = 450500;

properties[7] = new AvailableProperty();


properties[7].PropertyNumber = 93857;
properties[7].PropertyType = "Single Family";
properties[7].Address = "9047 Woodyard Road";
properties[7].City = "York";
properties[7].State = "PA";
properties[7].ZIPCode = 17405;
properties[7].Bedrooms = 4;
properties[7].Bathrooms = 2.5F;
properties[7].MarketValue = 326885;

properties[8] = new AvailableProperty();


properties[8].PropertyNumber = 930755;
properties[8].PropertyType = "Condominium";
properties[8].Address = "3842 Accolade Avenue #1206";
properties[8].City = "Alexandria";
properties[8].State = "VA";
properties[8].ZIPCode = 22231;
properties[8].Bedrooms = 3;
properties[8].Bathrooms = 2.0F;
properties[8].MarketValue = 525885;

properties[9] = new AvailableProperty();


properties[9].PropertyNumber = 240875;
properties[9].PropertyType = "Townhouse";
properties[9].Address = "842 Hempton Street";
properties[9].City = "Charlestown";
properties[9].State = "WV";
properties[9].ZIPCode = 25414;
properties[9].Bedrooms = 3;
properties[9].Bathrooms = 2.5F;
properties[9].MarketValue = 212500;

properties[10] = new AvailableProperty();


properties[10].PropertyNumber = 940075;
properties[10].PropertyType = "Single Family";
properties[10].Address = "4813 Woodland Court";
properties[10].City = "Falls Church";
properties[10].State = "VA";
properties[10].ZIPCode = 22042;
properties[10].Bedrooms = 5;
properties[10].Bathrooms = 3.5F;
properties[10].MarketValue = 645860;

properties[11] = new AvailableProperty();


properties[11].PropertyNumber = 931475;
properties[11].PropertyType = "Townhouse";
properties[11].Address = "5030 Goodson Road";
properties[11].City = "Arlington";
properties[11].State = "VA";
properties[11].ZIPCode = 22203;
properties[11].Bedrooms = 4;
properties[11].Bathrooms = 3.5F;
properties[11].MarketValue = 435775;

properties[12] = new AvailableProperty();


properties[12].PropertyNumber = 248095;
properties[12].PropertyType = "Condominium";
properties[12].Address = "9182 Weston Ave NW #F14";
properties[12].City = "Washington";
properties[12].State = "DC";
properties[12].ZIPCode = 20016;
properties[12].Bedrooms = 2;
properties[12].Bathrooms = 1.0F;
properties[12].MarketValue = 425665;

properties[13] = new AvailableProperty();


properties[13].PropertyNumber = 293705;
properties[13].PropertyType = "Single Family";
properties[13].Address = "12404 Livingston Boulevard";
properties[13].City = "Martinsburg";
properties[13].State = "WV";
properties[13].ZIPCode = 25401;
properties[13].Bedrooms = 4;
properties[13].Bathrooms = 2.50F;
properties[13].MarketValue = 225660;

properties[14] = new AvailableProperty();


properties[14].PropertyNumber = 937905;
properties[14].PropertyType = "Condominium";
properties[14].Address = "2039 Gonnard Road E5";
properties[14].City = "Laurel";
properties[14].State = "MD";
properties[14].ZIPCode = 20747;
properties[14].Bedrooms = 2;
properties[14].Bathrooms = 2;
properties[14].MarketValue = 275880;
}
}
}
3. Return to the form
4. On the form, double-click the Show button and implement its Click event as follows:

private void btnShow_Click(object sender, EventArgs e)


{
lbxPropertyNumbers.Items.Clear();
lbxAddresses.Items.Clear();
lbxCities.Items.Clear();
lbxStates.Items.Clear();
lbxZIPCodes.Items.Clear();
lbxBedrooms.Items.Clear();
lbxBathrooms.Items.Clear();
lbxMarketValues.Items.Clear();

if (lbxPropertiesTypes.CheckedItems.Contains("Single Families"))
{
foreach (AvailableProperty prop in properties)
{
if (prop.PropertyType == "Single Family")
{
lbxPropertyNumbers.Items.Add(prop.PropertyNumber.ToSt
ring());
lbxAddresses.Items.Add(prop.Address);
lbxCities.Items.Add(prop.City);
lbxStates.Items.Add(prop.State);
lbxZIPCodes.Items.Add(prop.ZIPCode);
lbxBedrooms.Items.Add(prop.Bedrooms);
lbxBathrooms.Items.Add(prop.Bathrooms);
lbxMarketValues.Items.Add(prop.MarketValue);
}
}
}

if (lbxPropertiesTypes.CheckedItems.Contains("Townhouses"))
{
foreach (AvailableProperty prop in properties)
{
if (prop.PropertyType == "Townhouse")
{
lbxPropertyNumbers.Items.Add(prop.PropertyNumber.ToSt
ring());
lbxAddresses.Items.Add(prop.Address);
lbxCities.Items.Add(prop.City);
lbxStates.Items.Add(prop.State);
lbxZIPCodes.Items.Add(prop.ZIPCode);
lbxBedrooms.Items.Add(prop.Bedrooms);
lbxBathrooms.Items.Add(prop.Bathrooms);
lbxMarketValues.Items.Add(prop.MarketValue);
}
}
}

if (lbxPropertiesTypes.CheckedItems.Contains("Condominiums"))
{
foreach (AvailableProperty prop in properties)
{
if (prop.PropertyType == "Condominium")
{
lbxPropertyNumbers.Items.Add(prop.PropertyNumber.ToSt
ring());
lbxAddresses.Items.Add(prop.Address);
lbxCities.Items.Add(prop.City);
lbxStates.Items.Add(prop.State);
lbxZIPCodes.Items.Add(prop.ZIPCode);
lbxBedrooms.Items.Add(prop.Bedrooms);
lbxBathrooms.Items.Add(prop.Bathrooms);
lbxMarketValues.Items.Add(prop.MarketValue);
}
}
}
}
5. Return to the form and double-click the Close button
6. Implement its event as follows:

private void btnClose_Click(object sender, EventArgs e)


{
Close();
}

7. Execute the application and test the checked list box


8. Close the form and return to your programming environment
9. To make sure that when a user clicks an item in one list box, the corresponding item gets selecte
boxes, on the form, click the Prop # list box
10. Press and hold Shift
11. Click each of the other list boxes
12. Release Shift
13. In the Properties window, click the Events button and double-click SelectedIndexChanged
14. Implement the event as follows:

private void lbxPropertyNumbers_SelectedIndexChanged(object sender,


EventArgs e)
{
lbxMarketValues.SelectedIndex =
lbxBathrooms.SelectedIndex =
lbxBedrooms.SelectedIndex =
lbxZIPCodes.SelectedIndex =
lbxStates.SelectedIndex =
lbxCities.SelectedIndex =
lbxAddresses.SelectedIndex =
lbxPropertyNumbers.SelectedIndex;
}
15. Return to the form

Automatically Checking an Item When Clicked


From its default implementation, when a checked list box is presented to the user, when an item is cl
highlighted but no check mark is put in the box. To put a check mark on the item, the user must click
an anomaly. It is purposely so the user would know the difference between an item that is selec
checked.

To support the ability to automatically put a check mark on an item when the user clicks it, the Chec
the CheckOnClick Boolean property. Its default value is False. If you want the items to be autom
this property to true.

On an existing checked list box, to find out if the its items are automatically checked, get the value
property.

Practical Learning: Automatically Checking an Item


1. On the form, click the checked list box
2. In the Properties window, double-click CheckOnClick to set its value to True
3. Save the form

3-D Checked Items


After creating the list, each item appears with a flat check box to its left. If you want a 3-D check b
the Boolean ThreeDCheckBoxes property from its False default to a True value:

ThreeDCheckBoxes
False True

Context Menus :

Practical Learning: Introducing Contextual Menus


1. From the Menus & Toolbars section of the Toolbox, click ContextMenuStrip
and click the form
2. While the context menu strip is still selected, in the Properties window click
(Name) and type mnuWithProperties
3. Then click Items and click its ellipsis button
4. Under the Select Item And Add To List combo box, make sure MenuItem is
selected and click Add
5. On the right side, click Text and type Edit
6. Click (Name) and type mnuEditProperty
7. On the left side, click Add and, on the right side, change the properties as
follows:
Text: Delete
(Name): mnuDeleteProperty
8. On the left side, click Add and, on the right side, change the properties as
follows:
Text: Clear
(Name): mnuClearProperties

9. Click OK
10. From the Menus & Toolbars section of the Toolbox, click ContextMenuStrip
and click the form
11. While the context menu strip is still selected, in the Properties window click
(Name) and type mnuNoProperty
12. On the form, under ContextMenuStrip, click Type Here
13. Type New Property and press Enter
14. On the form, under ContextMenuStrip, click New Property
15. In the Properties window, click (Name), type mnuNewProperty and press
Enter
Using a Contextual Menu
By default, a newly created contextual menu is attached neither to the form nor to
any control on it. In order to display a context menu, you must assign its name to
the control. To support this, Control, the ancestor to all visual controls of the .NET
Framework, is equipped, and provides to its children, a property named
ContextMenuStrip, which is of type ContextMenuStrip.

To visually assign a contextual menu to a control during design, click the control.
In the Properties window, click the ContextMenuStrip field, then click the arrow of
its combo box, and select the menu. If you had created more than one contextual
menu, the combo box would show all of them and you can choose the one you
want to use as default.

To programmatically specify the contextual menu of a control, assign a


ContextMenuStrip object to its ContextMenuStrip property. Here is an
example:

void InitializeComponent()
{
System.Windows.Forms.ContextMenuStrip context =
new System.Windows.Forms.ContextMenuStrip();

ToolStripMenuItem mnuCut = new ToolStripMenuItem("Cut");


ToolStripMenuItem[] mnuEdit =
{
new ToolStripMenuItem("Copy"),
new ToolStripMenuItem("Paste")
};

context.Items.Add(mnuCut);
context.Items.AddRange(mnuEdit);

ContextMenuStrip = context;
}

After assigning a ContextMenuStrip object to a control, when you right-click


(actually when the user right-clicks) the control, the contextual menu would
display. The above code would produce:
Practical Learning: Creating a Context Menu
1. Right-click the form and click View Code
2. Just above the Form1 constructor, declare a ListViewItem variable named
itmSelected

namespace AltairRealtors3
{
public partial class Form1 : Form
{
ListViewItem itmSelected;

public Form1()
{
InitializeComponent();
}

. . . No Change

}
3. Return to the form
4. Double-click an unoccupied area of the form to generate its Load event and
implement it as follows:

private void Form1_Load(object sender, EventArgs e)


{
itmSelected = new ListViewItem();
lvwProperties.ContextMenuStrip = mnuNoProperty;
}
5. Return to the form and click the list view
6. In the Properties window, click the Events button and double-click
MouseDown
7. Implement the event as follows:

private void lvwProperties_MouseDown(object sender, MouseEventArgs e)


{
if (e.Button == MouseButtons.Right)
{
if (lvwProperties.SelectedItems.Count > 0)
itmSelected = lvwProperties.SelectedItems[0];
else
itmSelected = null;
}
}
8. Return to the form

Coding Contextual Menus


In your application, you can create as many contextual menus as you want. If you
have different controls, each can have its own contextual menu or many can share
a contextual menu. Also, you can use different contextual menus for a control and
decide what menu to display when/why.

There is nothing particularly specific with writing code for a popup menu item. You
approach it exactly as if you were dealing with a menu item of a main menu. You
can write code for an item of a popup menu independent of any other item of a
main menu. If you want an item of a popup menu to respond to the same request
as an item of a main menu, you can write code for one of the menu items (either
the item on the main menu or the item on the popup menu) and simply call its
Click event in the event of the other menu item.

Practical Learning: Using Various Contextual Menus


1. On the form, click the list view if necessary.
In the events section of the Properties window, double-click
ItemSelectionChanged
2. Implement the event as follows:

private void lvwProperties_ItemSelectionChanged(object sender,


ListViewItemSelectionChangedEventArgs e)
{
if (e.Item == itmSelected)
lvwProperties.ContextMenuStrip = mnuNoProperty;
else
lvwProperties.ContextMenuStrip = mnuWithProperties;
}
3. Return to the form
4. Under the form, click mnuWithProperties
5. On the form, double-click Edit and implement its event as follows:

private void mnuEditProperty_Click(object sender, EventArgs e)


{
// Prepare to open the AvailableProperties dialog box
RealEstateProperty dlgProperty = new RealEstateProperty();

// Make sure an item, and only one, is selected


if ((lvwProperties.SelectedItems.Count == 0) ||
(lvwProperties.SelectedItems.Count > 1))
return;

// Identify the item that is currently selected


ListViewItem lviCurrent = lvwProperties.SelectedItems[0];

// Display the ItemDetails dialog box with the item number


dlgProperty.txtPropertyNumber.Text = lviCurrent.Text;
dlgProperty.cbxPropertyTypes.Text = lviCurrent.SubItems[1].Text;
dlgProperty.txtAddress.Text = lviCurrent.SubItems[2].Text;
dlgProperty.txtCity.Text = lviCurrent.SubItems[3].Text;
dlgProperty.cbxStates.Text = lviCurrent.SubItems[4].Text;
dlgProperty.txtZIPCode.Text = lviCurrent.SubItems[5].Text;
dlgProperty.txtBedrooms.Text = lviCurrent.SubItems[6].Text;
dlgProperty.txtBathrooms.Text = lviCurrent.SubItems[7].Text;
dlgProperty.txtMarketValue.Text = lviCurrent.SubItems[8].Text;

if (dlgProperty.ShowDialog() == DialogResult.OK)
{
lvwProperties.SelectedItems[0].Text =
dlgProperty.txtPropertyNumber.Text;
lvwProperties.SelectedItems[0].SubItems[1].Text =
dlgProperty.cbxPropertyTypes.Text;
lvwProperties.SelectedItems[0].SubItems[2].Text =
dlgProperty.txtAddress.Text;
lvwProperties.SelectedItems[0].SubItems[3].Text =
dlgProperty.txtCity.Text;
lvwProperties.SelectedItems[0].SubItems[4].Text =
dlgProperty.cbxStates.Text;
lvwProperties.SelectedItems[0].SubItems[5].Text =
dlgProperty.txtZIPCode.Text;
lvwProperties.SelectedItems[0].SubItems[6].Text =
dlgProperty.txtBedrooms.Text;
lvwProperties.SelectedItems[0].SubItems[7].Text =
dlgProperty.txtBathrooms.Text;
lvwProperties.SelectedItems[0].SubItems[8].Text =
dlgProperty.txtMarketValue.Text;
}
}
6. Return to the form
7. On the form, double-click Delete and implement its event as follows:

private void mnuDeleteProperty_Click(object sender, EventArgs e)


{
if (lvwProperties.SelectedItems.Count == 0)
return;

DialogResult answer = MessageBox.Show("Are you sure you want " +


"to delete that property?",
"Delete Property",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question);

if (answer == DialogResult.Yes)
lvwProperties.SelectedItems[0].Remove();
}
8. Return to the form
9. On the form, double-click Clear and implement its event as follows:

private void mnuClearProperties_Click(object sender, EventArgs e)


{
DialogResult answer = MessageBox.Show("Are you sure you want " +
"to delete all
properties?",
"Remove all Properties",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question);

if (answer == DialogResult.Yes)
lvwProperties.Items.Clear();
}
10. Return to the form
11. Under the form, click mnuNoProperty
12. On the form, under ContextMenuStrip, double-click New Property and
implement its event as follows:

private void mnuNewProperty_Click(object sender, EventArgs e)


{
mnuFileNewProperty_Click(sender, e);
}
13. Execute the application and test it
14. Right-click an empty line of the list view to see the contextual menu and click
New Property
15. Right-click the list view and click Edit
16. Right-click a row on the form and click Delete
17. Accept to delete the property
18. Close the form and return to your programming environment

Domain:

Creating a Domain Up-Down Control


At design time, to get a domain up-down control, from the Toolbox, you can click
the DomainUpDown button and click the form. To programmatically create a
domain up-down control, declare a variable of type DomainUpDown, initialize it
and add it to the Controls property of the container that will hold it. Here is an
example:

using System;
using System.Drawing;
using System.Windows.Forms;
public class Exercise : System.Windows.Forms.Form
{
DomainUpDown spnNames;

public Exercise()
{
InitializeComponent();
}

private void InitializeComponent()


{
spnNames = new DomainUpDown();

Controls.Add(spnNames);
}
}

public class Program


{
static int Main()
{
System.Windows.Forms.Application.Run(new Exercise());
return 0;
}
}

This would produce:

You might also like