Professional Documents
Culture Documents
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.
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
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
CREATE a DATABASE
The command used to create a database in SQL uses the following formula:
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
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
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
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].
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:
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();
}
string strConnection =
"Data Source=(local);Integrated Security=yes";
connection.Open();
command.ExecuteNonQuery();
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
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.
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;
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();
}
}
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:
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:
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
connection.Open();
command.ExecuteNonQuery();
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.
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.
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.
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.
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.
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();
}
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
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.
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.
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.
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.
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.
-- =============================================
-- 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:
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.
You create a check constraint at the time you are creating a table.
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.
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:
connection.Open();
command.ExecuteNonQuery();
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.
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.
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.
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.
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();
}
SqlCommand cmdSolasPropertyRental1 =
new SqlCommand(strSolasPropertyRental,
cnnSolasPropertyRental);
cnnSolasPropertyRental.Open();
cmdSolasPropertyRental1.ExecuteNonQuery();
cnnSolasPropertyRental.Open();
cmdSolasPropertyRental1.ExecuteNonQuery();
• On the main menu, you can click Data -> Add Data Source...
• In the Data Source window:
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.
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.
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.
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:
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
• 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
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.
To use the SqlDataAdapter class, you can declare a variable of type SqlDataAdapter using one
such as the default constructor. Here is an example:
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:
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:
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:
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:
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:
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:
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:
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
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:
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:
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:
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.
cnnVideos.Open();
SqlDataAdapter dadVideoCollection = new SqlDataAdapter(cmdVideos);
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.
cnnVideos.Open();
SqlDataAdapter dadVideoCollection = new
SqlDataAdapter(cmdVideos);
cnnVideos.Close();
}
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.
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.
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();
}
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.
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();
}
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
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
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.
In the SQL, data entry is performed using the INSERT combined with the
VALUES keywords. The primary statement uses the following syntax:
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:
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.
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
connection.Open();
command.ExecuteNonQuery();
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.
connection.Open();
command.ExecuteNonQuery();
If you find out that a record is not necessary, not anymore, or is misplaced,
you can remove it from a table.
In SQL, to delete a record, use the DELETE FROM statement associated with the WHERE operator. T
is:
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).
To programmatically delete a group or records, apply the DELETE FROM table formula and use a W
can identify each one of the records.
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.
connection.Open();
command.ExecuteNonQuery();
Close();
}
4. Return to your programming environment and change the code of the Close button as follows
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.
In SQL, the primary formula of the UPDATE statement as introduced on our formula can be used to
Here is an example:
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:
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:
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
Here is an example:
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
By convention or tradition, the name of the primary starts with PK_ followed by the name of th
example:
USE Exercise2;
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
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
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();
}
conYNB.Open();
cmdYNB.ExecuteNonQuery();
conYNB.Open();
cmdYNB.ExecuteNonQuery();
MessageBox.Show("A table named RentalRates has been
created");
}
conYNB.Open();
cmdYNB.ExecuteNonQuery();
MessageBox.Show("A table named Employees has been
created");
}
conYNB.Open();
cmdYNB.ExecuteNonQuery();
MessageBox.Show("A table named Customers has been
created");
}
conYNB.Open();
cmdYNB.ExecuteNonQuery();
MessageBox.Show("A table named Cars has been
created");
}
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
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.
7. Click Close
8. Save and close the table
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:
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:
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:
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).
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.
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:
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.
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:
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.
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:
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
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:
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();
}
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
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:
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:
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");
}
lblNewOperation_Click(sender, e);
}
6. Return to the form and double-click Quit
7. Implement its event as follows:
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
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:
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:
tbrSlider.Value = 6;
Controls.Add(tbrSlider);
}
tbrSlider.Minimum = 8;
tbrSlider.Maximum = 140;
tbrSlider.Value = 86;
Controls.Add(tbrSlider);
}
You can also set the minimum and the maximum values by calling the TrackBar.SetRange()
method. Its syntax is:
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:
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.
Controls.Add(tbrSlider);
}
When this happens, you can reduce the number of ticks. This is done using the TickFrequency
property. Here is an example:
tbrSlider.TickFrequency = 10;
Controls.Add(tbrSlider);
}
tbrSlider.TickStyle = TickStyle.TopLeft;
Controls.Add(tbrSlider);
}
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):
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;
public Form1()
{
InitializeComponent();
}
tbrImages.Value = 0;
}
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.
-- =============================================
-- Database: ynb1
-- For: Yugo National Bank
-- Author: FunctionX
-- Date Created: Monday 24 April 2007
-- =============================================
USE master
GO
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
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
namespace YNBTimeSheet2
{
public partial class Form1 : Form
{
bool ValidTimeSheet;
bool bNewRecord;
string strTimeSheetCode;
public Form1()
{
InitializeComponent();
}
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);
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();
}
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;
conTimeSheet =
new SqlConnection("Data
Source=(local);Database='ynb1';" +
"Integrated Security=true");
SqlCommand cmdTimeSheet = new SqlCommand(strSQL, conTimeSheet);
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;
}
}
conTimeSheet.Open();
cmdTimeSheet.ExecuteNonQuery();
conTimeSheet.Close();
Label Employee #:
TextBox txtEmployeeNbr
TextBox txtHourlySalary
DateTimePicker dtpStartingDate
DateTimePicker dtpEndDate
Label Monday
Label Tuesday
Label Wednesday
Label Thursday
Label Friday
Label Saturday
Label Sunday
Label Hours
Label Amount
Label Regular
Label Overtime
Button btnClose
4. Double-click the Close button and implement its Click event as follows:
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:
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:
this.dtpStartingDate.Focus();
}
// Find the number of days that separate the start and end
TimeSpan timeDifference = dteEnd.Subtract(dteStart);
double fourteenDaysLater = timeDifference.Days;
this.dtpEndDate.Focus();
}
}
13. Return to the form. Double-click the Process It button and implement its Click
event as follows:
}
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();
}
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
TextBox txtCustName
Label Qty
Label Shirts
Label Pants
TextAlign: Right
TextBox txtTotalPants 0.00
ReadOnly: True
Label Dresses
TextAlign: Right
TextBox txtTotaldresses 4.55
ReadOnly: True
TextAlign: Right
TextBox txtTotalOrder 0.00
ReadOnly: True
Label TaxRate
Label %
TextAlign: Right
TextBox txtTaxAmount 0.00
ReadOnly: True
TextAlign: Right
TextBox txtNetPrice 0.00
ReadOnly: True
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)
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");
}
this->txtTotalPants->Text = subTotal.ToString("F");
}
27. Double-click the button for the dresses and implement its Click event as follows:
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");
}
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;
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
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.
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.
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;
public QuestionAnswer()
{
InitializeComponent();
}
case 2:
txtQuestion.Text = "How many feet before you make
a turn should " +
"you signal that you are going
to turn?";
break;
case 3:
txtQuestion.Text = "You are driving in an alley
at fifteen (15) " +
"miles per hour. You are";
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";
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:";
case 6:
txtQuestion.Text = "You wish to make a \"U\" turn
at an intersection " +
"controlled by a traffic light.
You should: ";
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:";
case 8:
txtQuestion.Text = "If you are driving out of an
alley " +
"or driveway, you must";
case 9:
txtQuestion.Text = "You are coming to an
intersection " +
"where there is a flashing
yellow traffic " +
"light. You should";
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?";
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:";
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";
case 14:
txtQuestion.Text = "You are pulling into the
street from a " +
"parallel parking space.
Before doing " +
"so, you should:";
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:";
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?";
case 18:
txtQuestion.Text = "How close to a fire hydrant
(fire plug) " +
"may you park a motor
vehicle?";
case 19:
txtQuestion.Text = "When the light is green and
the yellow " +
"light comes on as you
approach an " +
"intersection, you should";
case 20:
txtQuestion.Text = "A flashing red traffic light
signals means the same as:";
if (QuestionCounter != 0)
average = Sum / QuestionCounter;
string strCongratulations = "";
if (Found0 == true )
QuestionCounter--;
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:
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:
CurrentNumberOfQuestions = 0;
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:
frmAnswer.TotalNumberOfQuestions = numberOfQuestions;
frmAnswer.ShowDialog();
}
15. Display the first form again
16. Double-click the Close button and implement its event 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
33. Return to the form and double-click an unoccupied area of its body
34. Implement the event as follows:
Rental Project :
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.
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:
45.
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:
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:
}
28. Return to the form
29. Double-click the Close button and implement its event as follows:
dlgCar.btnPicture.Visible = true;
dlgCar.btnSubmit.Visible = true;
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:
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:
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:
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:
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:
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:
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");
}
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");
}
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:
Bank Project :
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;
cnnYNB.Open();
cmdYNB.ExecuteNonQuery();
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
Label Principal:
Label %
Label years
RadioButton rdoMonthly
RadioButton rdoQuarterly
RadioButton rdoSemiannually
RadioButton rdoAnnually
GroupBox Results
TextAlign: Right
TextBox txtFutureValue 0.00
ReadOnly: True
Charts:
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
Label Monday
Label Tuesday
Label Wednesday
Label Thursday
Label Friday
TextBox txtMonday 12000 TextAlign: Right
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();
}
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:
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();
}
Charts:
Windows Controls:
• Label
• Button
• Text Box
• Group Box
TextBox txtCurrentQtr1 0
TextBox txtCurrentQtr2 0
TextBox txtCurrentQtr3 0
TextBox txtCurrentQtr4 0
TextBox txtPreviousQtr1 0
TextBox txtPreviousQtr2 0
TextBox txtPreviousQtr3 0
TextBox txtPreviousQtr4 0
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();
}
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:
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");
}
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");
}
// 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);
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:
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");
}
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");
}
// 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);
graphDrawingArea.DrawRectangle(new Pen(Color.Black),
25, 380, Width - 220, 1);
Invalidate();
}
Bar Charts:
Windows Controls:
• Label
• Button
• Text Box
• Picture Box
Label Graduates
Label Undergraduates
Label Certificates
TextBox txtGraduates 0
TextBox txtUndergraduates 0
TextBox txtCertificates 0
PictureBox pbxChart
Label ____Legend____
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:
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:
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
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");
}
pbxChart.Invalidate();
}
32. Return to the form and double-click the Close button
33. Implement its event as follows:
File concept:
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();
}
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:
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:
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:
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:
if (!Directory.Exists(strDirectory))
Directory.CreateDirectory(strDirectory);
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:
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;
}
}
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:
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
3. Save everything
PriceEachTopping = double.Parse(txtEachTopping.Text);
PriceToppings = (Pepperoni + Sausage + ExtraCheese + Onions + Olives) *
PriceEachTopping;
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:
Price = double.Parse(txtPriceBread.Text);
CalculatePrice();
}
Price = double.Parse(txtPriceWings.Text);
CalculatePrice();
}
Price = double.Parse(txtPriceCan.Text);
CalculatePrice();
}
Price = double.Parse(txtPriceSoda20.Text);
CalculatePrice();
}
Price = double.Parse(txtPriceSoda2L.Text);
CalculatePrice();
}
Price = double.Parse(txtPriceOJ.Text);
CalculatePrice();
}
Price = double.Parse(txtPriceWater.Text);
CalculatePrice();
}
13. On the form, double-click the Close button and implement its Click event as follows:
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.
Windows Controls:
• Label
• Panel
• Button
• Text Box
• Group Box
• Scroll Bar
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
Label Red:
TextBox txtRed 0
Label Green:
TextBox txtGreen 0
Label Blue:
TextBox txtBlue 0
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();
}
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;
}
txtResult.Text = BD;
}
}
}
15. Return to the form and double-click the left scroll bar
16. Implement its event as follows:
pnlBody.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:
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:
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:
ClickOption(txtVLinkPreview.ForeColor,
txtVisitedLink.Text);
HexVLink = txtVisitedLink.Text;
}
34. Return to the form
35. Double-click the Copy button and implement it as follows:
Controls:
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.
using System;
namespace Algebra2
{
public class Algebra
{
public static long Factorial(long x)
{
if (x <= 1)
return 1;
else
return x * Factorial(x - 1);
}
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 Exercise()
{
InitializeComponent();
}
this.Controls.Add(btnResume);
}
}
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:
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:
Here is an example:
public Exercise()
{
InitializeComponent();
}
Controls.Add(btnResume);
}
}
4. Access the Factorial tab page and double-click its Calculate button
5. Implement the event as follows:
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:
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:
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:
Controls.Add(btnResume);
}
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:
Controls.Add(btnResume);
}
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.
• 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
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.
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 :
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 AvailableProperty()
{
}
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 Exercise()
{
InitializeComponent();
}
private void InitializeComponent()
{
lbxPersonalRelationships = new CheckedListBox();
lbxPersonalRelationships.Location = new Point(12, 12);
Controls.Add(lbxPersonalRelationships);
}
}
CheckedListBox lbxPropertiesTypes
Font:
Garamond,
Label Properties_______
15.75pt,
style=Bold
Label Prop #
Label Address
Label City
Label State
Label Beds
Label Baths
ListBox lbxPropertyNumbers
ListBox lbxAddresses
ListBox lbxCities
ListBox lbxStates
ListBox lbxZIPCodes
ListBox lbxBedrooms
ListBox lbxBathrooms
ListBox lbxMarketValues
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.
public Exercise()
{
InitializeComponent();
}
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);
}
}
Remember that you can also add an array of items by calling the AddRange() and you can inser
Insert() method.
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
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
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.
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();
}
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:
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.
ThreeDCheckBoxes
False True
Context Menus :
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.
void InitializeComponent()
{
System.Windows.Forms.ContextMenuStrip context =
new System.Windows.Forms.ContextMenuStrip();
context.Items.Add(mnuCut);
context.Items.AddRange(mnuEdit);
ContextMenuStrip = context;
}
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:
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.
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:
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:
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:
Domain:
using System;
using System.Drawing;
using System.Windows.Forms;
public class Exercise : System.Windows.Forms.Form
{
DomainUpDown spnNames;
public Exercise()
{
InitializeComponent();
}
Controls.Add(spnNames);
}
}