C# Programming Hands on Lab January 2011 For the latest information, please see bluejack.binus.ac.id
C# Programming
Hands on Lab
January 2011
For the latest information, please see bluejack.binus.ac.id
i | P a g e
Information in this document, including URL and other Internet Web site references, is
subject to change without notice. This document supports a preliminary release of software
that may be changed substantially prior to final commercial release, and is the proprietary
information of Binus University.
This document is for informational purposes only. BINUS UNIVERSITY MAKES NO
WARRANTIES, EITHER EXPRESS OR IMPLIED, AS TO THE INFORMATION IN THIS
DOCUMENT.
The entire risk of the use or the results from the use of this document remains with the
user. Complying with all applicable copyright laws is the responsibility of the user. Without
limiting the rights under copyright, no part of this document may be reproduced, stored in
or introduced into a retrieval system, or transmitted in any form or by any means
(electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without
the express written permission of Binus University.
Binus University may have patents, patent applications, trademarks, copyrights, or other
intellectual property rights covering subject matter in this document. Except as expressly
provided in any written license agreement from Binus University, the furnishing of this
document does not give you any license to these patents, trademarks, copyrights, or other
intellectual property.
Unless otherwise noted, the example companies, organizations, products, domain names, e-
mail addresses, logos, people, places and events depicted herein are fictitious, and no
association with any real company, organization, product, domain name, email address,
logo, person, place or event is intended or should be inferred.
© 2011 Binus University. All rights reserved.
The names of actual companies and products mentioned herein may be the trademarks of
their respective owners.
ii | P a g e
Table of Contents
OVERVIEW .................................................................................................... iii
SYSTEM REQUIREMENT ................................................................................... iv
Chapter 01 – IDE dan Instruksi I/O ........................ Error! Bookmark not defined.
Chapter 02 – Operasi Aritmatika ........................... Error! Bookmark not defined.
Chapter 03 – Struktur Kendali Pemilihan ......................................................... 20
Chapter 04 – Struktur Kendali Perulangan ....................................................... 30
Chapter 05 – Array ....................................................................................... 36
Chapter 06 – Function .................................................................................. 45
Chapter 07 – Built-in Function ........................................................................ 58
Chapter 08 – Rekursif ................................................................................... 64
Chapter 09 – Operasi File .............................................................................. 68
Chapter 10 – Sorting .................................................................................... 75
Chapter 11 – String ...................................................................................... 82
iii | P a g e
OVERVIEW
Chapter 01
• Visual C# .NET Introduction
Chapter 02
• Data Type, Array, and Operator
Chapter 03
• Control Structure
Chapter 04
• Method
Chapter 05
• Object Oriented Programming
Chapter 06
Graphical User Interface Basic
Chapter 07
• Graphical User Interface Intermediate
Chapter 08
• Graphical User Interface Advanced
Chapter 09
• Database Application
Chapter 10
• Report Service
Chapter 11
• Character, String, and Regular Expression
iv | P a g e
Chapter 12
• Working With Files
1 | P a g e
Chapter 01
Visual C# .NET Introduction
2 | P a g e
Introduction to .NET Environtment
The Microsoft .NET Framework is a platform for building, deploying, and running Web
Services and applications. It provides a highly productive, standards-based, multi-language environment for integrating existing investments with next-generation applications and
services as well as the agility to solve the challenges of deployment and operation of Internet-scale applications. The .NET Framework consists of three main parts: the common
language runtime, a hierarchical set of unified class libraries, and a componentized version of Active Server Pages called ASP.NET.
The Microsoft .NET Framework is a managed code programming model for building applications on Windows clients, servers, and mobile or embedded devices. Developers use
.NET to build applications of many types: Web applications, server applications, smart client applications, console applications, database applications, and more.
.NET is essentially a system application that runs on Windows. The heart of .NET is
the .NET Framework. The most important component of the framework is the CLR as the heart and soul of the .NET architecture. Every application written using the Framework
depends on the CLR. Among other things, the CLR provides a common set of data types,
acting as a foundation for C#, VB, and all other languages that target the .NET Framework. Because this foundation is the same no matter which language they choose, developers see
a more consistent environment.
The CLS is a statement of rules that allow each language to interoperate. For
example, the CLS guarantees that Visual Basic‟s idea of an integer is the same as C#. Because the two languages agree on the format of the data, they can transparently share
the data. The CLS defines not only type information, but also method invocation, error handling, and so forth.
You can define a class in Visual Basic and use it in C#. A method that is defined in C# can be called by Visual Basic or any other language that adheres to the CLS. After an
API is learned in one language, then using that API in any other CLS-compliant language is virtually the same.
The middle layer called Application Class Libraries and Services. This layer represents
the rich set of libraries and APIs that have been created to support virtually all aspects of
3 | P a g e
programming. Graphical user interface APIs or Windows.Forms, database APIs through
ADO.NET, XML processing, regular expression handling, and so forth are all part of this layer.
Visual Studio .NET is an important part of the .NET Framework because it provides a
means for the programmer to access the framework at any level. A programmer can use Visual Studio .NET to write code in many supported managed languages, or he can bypass
the CLR altogether and write unmanaged code with Visual Studio .NET.
On the left in the figure, you can see the four languages that Microsoft has
announced it will provide support for “out of the box.” The ellipsis signifies the other significant and growing set of languages that support the Common Language Specification
(CLS) and are full participants in the .NET Framework. Applications written in any .NET language can use the code in the .NET Framework class library. Among the most important
technologies provided in this library are the following:
a. ASP.NET: Classes focused on building browser-accessible applications.
b. Windows Forms: Classes for building Windows graphical user interfaces (GUIs) in any CLR-based programming language.
c. ASP.NET Web Services (also called ASMX): Classes for creating applications that communicate with other applications using Web services.
d. Enterprise Services: Classes that provide distributed transactions, object instance
control, and other services useful for building reliable, scalable applications. e. ADO.NET: Classes focused on accessing data stored in relational database
management systems (DBMS).
Introduction to C# Programming
Microsoft's original plan was to create a rival to Java, named J++ but this was abandoned to create C#. Although C# is derived from the C programming language, it has
features such as garbage collection that allow beginners to become proficient in C# more quickly than in C or C++. Similar to Java, it is object-oriented, comes with an extensive
class library, and support, and generics, make C# a good choice for many types of software development projects: rapid application development projects, projects implemented by
individuals or large or small teams, Internet applications, and projects with strict reliability
requirements. Testing programming errors that are common in weakly typed languages.
A large part of the power of C# (as with other .NET languages), comes with the common .NET Framework API, which provides a large set of classes, including ones for
4 | P a g e
encryption, TCP/IP socket programming, and graphics. Developers can thus write part of an
application in C# and another part in another .NET language (e.g. VB.NET), keeping the tools, library, and object-oriented development model while only having to learn the new
language syntax.
Because of the similarities between C# and the C family of languages, as well as Java, a developer with a background in object-oriented languages like C++ may find C#
structure and syntax intuitive.
C# and other .NET languages rely on an implementation of the virtual machine
specified in the Common Language Infrastructure, like Microsoft‟s Common Language Runtime (CLR). That virtual machine manages memory, handles object references, and
performs Just-In-Time (JIT) compiling of Common Intermediate Language code. The virtual machine makes C# programs safer than those that must manage their own memory and is
one of the reasons .NET language code is referred to as managed code. More like Java than C and C++, C# discourages explicit use of pointers, which could otherwise allow software
bugs to corrupt system memory and force the operating system to halt the program forcibly with nondescript error messages.
Compile, Run & Debug
a. Compile
To transform a program written in a high-level programming language from source code
into object code. Programmers write programs in a form called source code. Source code must go through several steps before it becomes an executable program. The first step
is to pass the source code through a compiler, which translates the high-level language intructions into object code.
The final step in producing an executable program after the compiler has produced object code is to pass the object code through a linker. The linker combines modules
and gives real values to all symbolic addresses, thereby producing machine code.
b. Run & Debug Debugging is a methodical process of finding and reducing the number of bugs, or
defects, in a computer program or a piece of electronic hardware, thus making it behave as expected. Debugging tends to be harder when various subsystems are tightly
coupled, as changes in one may cause bugs to emerge in another.
5 | P a g e
You can compile, run & debug your program on Visual Studio by pressing [CTRL] + [F5] (compile & run without debugging) or only [F5] (compile & run with debugging) on your
keyboard.
In this chapter, you will learn how to create a console application using C# which is one of Visual Studio components. Visual Studio includes an Application Wizard that builds
template programs.
The following instructions are for Visual Studio. If you use anything other than Visual
Studio, you have to refer to the documentation that came with your environtment. Alternatively, you can just type the source code directly into your C# environtment.
Start Visual Studio on your directory. Normally you can choose Start All Programs
Microsoft Visual Studio xxxx Microsoft Visual Studio xxxx. [xxxx] refers to the version
of your Visual Studio.
Complete these steps to create your C# console application:
a. Choose File New Project on the menu to create a new project.
6 | P a g e
Visual Studio requires you to create a project before you can start to enter
your C# program. A project is like a bucket in which you throw all the files that go into making your program. When you tell your compiler to build
(compile) the program, it sorts through the project to find the files it needs in order to re-create the executable program.
b. From New Project window, click the Console Application icon and set
the Name, Location, and Solution name fields.
Set the Name field as your project name and the Location field as the project
directory. Normally the Solution name field will automatically filled similar as
you set the value of the Name field.
c. Click the OK button. After a bit of disk whirring and chattering, Visual Studio generates a file called
Program.cs.
7 | P a g e
You will start your code inside the static void Main method block / scope
(between the open and close brace „{}‟).
Try to run your first console application by pressing [CTRL] + [F5] (compile
without debugging) or only [F5] (compile with debugging) on your keyboard.
And your program still does nothing.
Basic C# Syntax
You will need input / output to make one or more process on your program.
8 | P a g e
You may want your program to display some output in text form. In order to do that,
put the following statement inside the Main method block.
And you will see the output on your program.
You just use two of built-in method on C#. Write and WriteLine method are common
method use for displaying outputs in text form. The Write method displays the text without
a new line, while the WriteLine method displays with it. The Console statement means a
class that has both Write and WriteLine method, you will learn more about method and
class in the next more chapter.
Before further explanation you may want to know some of common method from Console class.
Name Return Type Parameters Notes
Console.ReadLine() string none Reads the next line of characters
9 | P a g e
from the standard input stream.
Console.Read() int none Reads the next character from the standard input stream.
Console.Clear() void none Clears the console buffer and corresponding console window of
display information.
Console.Write() void +17 overloads Writes the specified string value to
the standard output stream.
Console.WriteLine() void +18 overloads Writes the text representation of the specified array of objects, followed
by the current line terminator, to the standard output stream using the
specified format information.
You will learn about return type and parameters in the next more chapter.
During the study about output, you also need to know about escape sequences. An escape sequence is a series of characters used to change the state of computers and their
attached peripheral devices. These are also known as control sequences, reflecting their use
in device control. Some control sequences are special characters that always have the same meaning. Escape sequences use an escape character to change the meaning of the
character which follow it, meaning that the characters can be interpreted as a command to be executed rather than as data.
C# defines the following character escape sequences:
Escape Character Notes
\ ' Display a single quote, needed for character literals.
\ " Display a double quote, needed for string literals.
\\ Display a backslash on the screen.
\0 Unicode character 0.
\a Alert (character 7).
\b Backspace (character 8).
\f Form feed (character 12).
\n New line (character 10).
\r Carriage return (character 13).
\t Horizontal tab (character 9).
\v Vertical quote (character 11).
\uxxxx Unicode escape sequence for character with hex value xxxx.
\xn [n] [n] [n] Unicode escape sequence for character with hex value nnnn (variable length version of \uxxxx).
\Uxxxxxxxx Unicode escape sequence for character with hex value xxxxxxxx (for generating surrogates).
Use these escape sequences with backslash as the first character. Try the following code.
10 | P a g e
Run the program and see the result.
You will also need comments / documentations on your source code.
The green codes will be ignored by the compiler.
Chars Notes
// One line comments.
/**/ More than one line comments.
You can use Console.ReadLine() to make your program waits input from user. But
you will need to declare variables that holds the input values, so that you can use them for
further process of your program. Data type is neccesary to declare a variable. For now, you just know the data type string that holds texts. Try the following code.
11 | P a g e
Run the program. The program will ask for your name.
Try to input your name.
Type [ENTER]. The program will clear the current text followed by the output. And your name will be displayed.
2. Exercise
For exercise, you‟ll have to make a program of product registration. This program will asks several questions about the product informations.
After user inputs all informations, the program will clears the current text and displays the
information of new product.
12 | P a g e
Answer
a. Task 1: Declare necessary variables:
We need two variables that holds product ID and name. We‟ll holds each of them with string type variable.
b. Task 2: Create input / output for the program to capture informations:
Create the title “Product Registration” and asks the user to input product informations.
c. Task 3: Displays the new product informations: Clear the current texts and show the new product informations which inputed by
user.
13 | P a g e
14 | P a g e
Chapter 02
Visual C# .NET Introduction
15 | P a g e
Data Types
In computer programming, a data type (or datatype) is a classification identifying
one of various types of data, such as floating-point (holds decimal values), integer, or boolean that determines the possible values for that type, the operations that can be done
on values of that type, and the way values of that type can be stored
Almost all programming languages explicitly include the notion of data type, though different languages may use different terminology. Common data types may include:
integers,
booleans, characters,
floating-point numbers, alphanumeric strings.
For example, in the Java programming language, the "int" type represents the set of
32-bit integeres ranging in value from -2,147,483,648 to 2,147,483,647, as well as the operations that can be performed on integers, such as addition, subtraction, and
multiplication.
Most programming languages also allow the programmer to define additional data
types, usually by combining multiple elements of other types and defining the valid operations of the new data type. For example, a programmer might create a new data type
named complex number that would include real and imaginary parts. A data type also represents a constraint placed upon the interpretation of data in a type system, describing
representation, interpretation and structure of values or objects stored in computer memory. The type system uses data type information to check correctness of computer
programs that access or manipulate the data.
C# is a strongly-typed language. Before a value can be stored in a variable, the type
of the variable must be specified, as in the following examples:
Note that the type must be specified both for simple, built-in types such as an int
and for complex or custom types such as XmlDocument.
C# includes support for the following built-in data types:
Data Type Notes
Class/Struct Alias
struct Byte byte 0 .. 255
struct Sbyte sbyte -128 .. 127
struct Int16 short -32,768 .. 32,767
struct Uint16 ushort 0 .. 65,535
struct Int32 int -2,147,483,648 .. 2,147,483,647
struct UInt32 uint 0 .. 4,294,967,295
struct Int64 long -9,223,372,036,854,775,808 .. 9,223,372,036,854,775,807
16 | P a g e
struct Uint64 ulong 0 .. 18,446,744,073,709,551,615
struct Single float -3.402823e38 .. 3.402823e38
struct Double double -1.79769313486232e308 .. 1.79769313486232e308
struct Decimal decimal -79228162514264337593543950335 ..
79228162514264337593543950335
struct Char char A Unicode character.
class String string A string of Unicode characters.
struct Boolean bool True or False.
class Object object An object.
Notes: class/struct describes the original form in the System namespace of the data type
you use. You can use the class/struct directly or simply use its alias.
Variables and Constants
Perhaps the most fundamental concept in programming is the concept of variables
and constants. You probably know that you'll need to deal with them a lot.
a. Variables Variables are essentially locations in computer memory that are reserved for storing the
data used by an application. Each variable is given a name by the programmer and assigned a value. The name assigned to the variable may then be used in the C# code
to access the value assigned to the variable. This access can involve either reading the value of the variable, or changing the value. It is, of course, the ability to change the
value of variables which gives them the name variable.
A variable must be declared as a particular type such as an integer, a character or a
string. C# is what is known as a strongly typed language in that once a variable has been declared as a particular type it cannot subsequently be changed to a different type.
While this may come as a shock to those familiar with loosely typed languages such as Ruby it will be familiar to Java, C and C++ programmers. Whilst it is not possible to
change the type of a variable it is possible to disguise the variable as another type under certain circumstances. This involves a concept known as casting and will be covered
later in this chapter.
Variable declarations require a type, a name and, optionally a value assignment. The
following example declares an integer variable called interestRate but does not initialize it:
The following example declares and initializes a variable using the assignment operator (=):
A new value may be assigned to a variable at any point after it has been declared.
17 | P a g e
b. Constants A constant is similar to a variable in that it provides a named location in memory to
store a data value. Constants differ in one significant way in that once a value has been assigned to a constant it cannot subsequently be changed.
Constants are particularly useful if there is a value which is used repeatedly throughout
the application code. Rather than use the value each time, it makes the code easier to read if the value is first assigned to a constant which is then referenced in the code. For
example, it might not be clear to someone reading your C# code why you used the
value 5 in an expression. If, instead of the value 5, you use a constant named interestRate the purpose of the value becomes much clearer. Constants also have the
advantage that the if the programmer needs to change a widely used value it only needs to be changed once in the constant declaration and not each time it is referenced.
As with variables, constants have a type, a name and a value. Unlike variables,
constants must be initialized at the same time that they are declared and must be prefixed with the const keyword:
Note that a constant, unlike a variable, must be initialized at the point that it is declared.
For example:
The above code will result in a compilation error along the lines of A const field requires
a value to be provided. Now that we have described C# variables and constants it is time to start looking at the different types that are available to us as C# programmers.
Array and Dimensional Array
Imagine that you want to enter 10 numbers and calculate their average. You would
need to declare 10 variables to do this. That is a lot of variables to have to declare and you still have to read the values in one at a time for each one. An easier way of doing this is to
use an array. An array is many variables grouped together under one name.
To declare an array you must first have the data type followed immediately by empty
square brackets. After that you put the array's name. Here is how to declare an array of integers called arr.
18 | P a g e
This is not an array yet but just a reference to an array. You must set the number of
dimensions using the new keyword followed by the data type again with square brackets after it that contain the number of elements you want in the array. The following example
creates an array with 3 elements.
The following table will help you imagine what an array looks like.
Index / Element Number Value
0 5
1 12
2 7
You must use square brackets after the name of the array to access its values. Inside the
square brackets you put the number of the element you want to access. The first array element is 0 and not 1 as you would think and the last element is 1 less than the size of the
array. Here is an example of how to set all 3 values of an array and how to print them.
You also can create multi-dimensional array. A multi-dimensional array is an array
that has elements in more than one dimension. A 2-dimensional can be thought of as
having both an x and a y dimension. You do get arrays with more than 2 dimensions but they are not used very often. Here is a table that will help you imagine what a 2-
dimensional array looks like.
0 1 2
0 1 2 3
1 4 5 6
2 7 8 9
When you declare a 2-dimensional array you must separate the dimensions with a comma. Here is an example of how you would declare a 2-dimensional array with 3 elements as the
size of each dimension.
You also use a comma when setting the value.
Array Sorting
19 | P a g e
This example shows how to sort arrays in C#. Array can be sorted using static
method Array.Sort which internally use Quicksort algorithm.
To sort array of primitive types such as int, double or string use method Array.Sort(arrayVal) with the array as a paramater. See example how to sort int array:
or how to sort string array:
Array Searching
C# lets you search for the first instance of an element in an array in case you need
to pass a particular element in your array to another part of your program or if you need to
get some specific information such as finding the number of times an element appears in an array.
You can search within an array using the Array.IndexOf method. This built-in
method returns the index number of the first array element that you want to search for. For example, if you search for the third element in an array, then the Array.IndexOf method
return the index number 2 because the default first index in an array is 0. If you set the first index number yourself, then the index number returned for your found element will
vary.
The Array.IndexOf method also lets you search for an array element within certain
index positions. For example, you can search for an array element that is the string and that
appears between index number 2 and 10. You can also search for an array element from an index position through the last element in the array.
The drawback to using the Array.IndexOf method is that you can only search within
single-dimensional array.
20 | P a g e
You may want to use the Array.Find method to declaratively search the arrays in
your program. You can specify a Predicate type instance to determine what logic the search
uses, and this allows you to use a for-loop without having to maintain loop indexes, easing maintenance. Here we dive into the Array.Find method and the similar method
Array.FindAll, which provide declarative searching functions.
Arithmetic Operator
There are five basic arithmetic operators available in C#. These are used for:
addition (+), subtraction (-),
multiplication (*), division (/),
modulus (%).
Of these, the first four are available to almost every programming language. Here
are some simple examples:
It is important to remember that the resultant value of a mathematical operation is subject to the rules of the receiving variable's data type. The result of a division operation
may yield a floating point value. However, if assigned to an integer the fractional part will be lost. Equally important, and less obvious, is the effect of an operation performed on
21 | P a g e
several integers and assigned to a non-integer. In this case, the result is calculated as an
integer before being implicitly converted. This means that although the resultant value is assigned to a floating point variable, the fractional part is still truncated unless at least one
of the values is explicitly converted first. The following examples illustrate this:
The last of the five arithmetic operators is modulus. This operator yields a value
equal to the remainder of an integer division. For example, when ten is divided by three the answer is three and the remainder is one. The modulus operator can be used with all
numeric data types.
You can also use postfix increment and decrement operators.
Assignment Operator
The assignment operators assign a new value to a variable, a property, or an indexer
element.
22 | P a g e
C# includes support for the following assignment operators :
Operator Notes
= Basic assignment operator Equivalent to: X = 2
*= Compound assignment operator Equivalent to: X = X * 2
/= Compound assignment operator Equivalent to: X = X / 2
%= Compound assignment operator Equivalent to: X = X % 2
+= Compound assignment operator Equivalent to: X = X + 2
-= Compound assignment operator Equivalent to: X = X - 2
<<= Compound assignment operator Equivalent to: X = X << 2
>>= Compound assignment operator Equivalent to: X = X >> 2
&= Compound assignment operator Equivalent to: X = X & 2
^= Compound assignment operator Equivalent to: X = X ^ 2
|= Compound assignment operator Equivalent to: X = X | 2
Logical and Bitwise Operator
C# defines the following logical and bitwise operators:
Operator Notes
& Bitwise AND of the two operands
| Bitwise OR of the two operands
^ Bitwise exclusive OR (XOR) of the two
operands
&& Logical AND of the two operands
|| Logical OR of the two operands
The operators &, |, and ^ are usually used on integer data types, though they can also be applied to the bool type.
The operators && and || differ from the single-character version in that they perform
short-circuit evaluation.
Comparison Operator
C# defines the following comparison operations:
23 | P a g e
Operator Notes
var1 == var2 Returns true if var1 is equal to var2
var1 != var2 Returns true if var1 is not equal to var2
var1 < var2 Returns true if var1 is less than var2
var1 <= var2 Returns true if var1 is less than or equal to var2
var1 > var2 Returns true if var1 is greater than var2
var1 >= var2 Returns true if var1 is greater than or equal to var2
These operators return a result of type bool. When performing a comparison
between two reference-type objects, the compiler will first look for relational operators defined on the objects. If it finds no applicable operator, and the relational is == or !=, the
appropriate relational operator will be called from the object class. This operator compares whether the two operands are the same object, not whether they have the same value.
For value types, the process is the same, except that the built-in relational operator
for value types compares each of the fields in the struct, and returns true if all the values
are identical. For the string type, the relational operators are overloaded so that == and !=
compare the values of the strings, not the references.
Operator Precedence
When an expression contains multiple operators, the precedence of the operators
controls the order in which the elements of the expression are evaluated. The default precedence can be changed by grouping elements with parentheses.
In C#, all binary operators are left-associative, which means that operations are performed left to right, except for the assignment and conditional (?:) operators, which are
performed right to left.
The following table summarizes all operators in precedence from highest to lowest.
24 | P a g e
Category Operators
Primary (x) x.y f(x) a[x] x++ x-- new typeof sizeof checked unchecked
Unary + - ! ~ ++x --x (T)x
Multiplicative * / %
Additive + -
Shift << >>
Relational < > <= >= is
Equality == !=
Logical AND &
Logical XOR ^
Logical OR |
Conditional AND &&
Conditional OR ||
Conditional ?:
Assignment = *= /= %= += -= <<= >>= &= ^= |=
3. Exercise
For exercise, you‟ll have to make a program of product registration. This program will asks several questions about the product informations. There are 2 products information
you should register.
Program will asks the first product informations.
The program will clears the current text and asks the second product.
After user inputs all informations, the program will clears the current text and displays
the information of new product with table view.
25 | P a g e
The program will asks, whether the user want to search or not.
Search process is, where the product name starts with the words on the keyword. The
program will clears the current text and display the search result.
Notes: All user‟s inputs is not validated yet !!
Answer
d. Task 1: Declare necessary variables on the Program class:
We need four array variables that holds product informations and three variable that
holds search informations.
e. Task 2: Create input / output for the program to capture informations:
26 | P a g e
Create the title “Product Rolex Registration” and asks the user to input product
informations. Clear the current texts.
f. Task 3: Displays the new product informations:
Display the new product informations which inputed by user with table view (use the string format to simplify creating table view). And do the arithmetic operation for
getting the wprice each row and total price in the end of the table.
27 | P a g e
g. Task 4: Create search process in the program:
User will input keyword. Use Array.Find method to get the search value and
Array.IndexOf to get the search index.
h. Task 5: Displays the search result:
You will use the search index for index in your arrays.
28 | P a g e
Chapter 03
Visual C# .NET Introduction
29 | P a g e
Selection Statement
The selection statements are used to perform operations based on the value of an
expression. a. If-else
The if statement in C# requires that the condition inside the if statement evaluate
to an expression of type bool.
b. Switch-case Switch statements have often been error-prone; it is just too easy to inadvertently
omit a break statement at the end of a case, or not to notice that there is fall-
through when reading code. C# gets rid of this possibility by requiring that there be
either a break at the end of every case block, or a go to another case label in the
switch.
30 | P a g e
c. Ternary Operator
Ternary use conditional operator (?:) and returns one of two values depending on the value of a Boolean expression.
Looping Statement
Looping / Iteration statements are used to perform operations while a specific
condition is true.
a. While
The while loop functions as expected: while the condition is true, the loop is
executed. Like the if statement, the while requires a Boolean condition:
The break statement may be used to exit the while loop, and the continue statement
may be used to skip to the closing brace of the while block for this iteration, and
then continue with the next iteration.
31 | P a g e
b. Do-while A do loop functions just like a while loop, except the condition is evaluated at the
end of the loop rather than the beginning of the loop.
Like the while loop, the break and continue statements may be used to control the
flow of execution in the loop.
c. For
A for loop is used to iterate over several values. The loop variable may be declared
as part of the for statement:
The scope of the loop variable in a for loop is the scope of the statement or
statement block that follows the for. It cannot be accessed outside of the loop
structure:
As with the while loop, the break and continue statements may be used to control
the flow of execution in the loop.
You can use a for loop as the index of array.
32 | P a g e
d. Foreach You have a collection in your C# program, such as an array of elements or a generic
collection. Use the foreach loop in the C# programming language to loop over the
elements in this reference variable, providing a powerful and simple way to enumerate the individual values with less complex syntax than the traditional for
loop.
In the foreach statement, you do not need to specify the loop bounds minimum or
maximum, and do not need an „i‟ variable as in for loops. This results in fewer
characters to type and code that it is easier to review and verify, with no functionality loss.
The reserved foreach keyword followed by a parenthetical containing the declaration
of the iteration variable. The iteration variable string value can be a different type
such as int number if you are looping over that type. You must specify the keyword
in and then the object to loop over. You can use a List, Dictionary, ArrayList,
custom collections, or any type of array to loop over.
Exception / Error Handling
Exception handling is an in built mechanism in .NET framework to detect and handle
run time errors. The .NET framework contains lots of standard exceptions. The exceptions are anomalies that occur during the execution of a program. They can be because of user,
logic or system errors. If a user (programmer) do not provide a mechanism to handle these anomalies, the .NET run time environment provide a default mechanism, which terminates
the program execution.
C# provides three keywords try, catch and finally to do exception handling. The try
encloses the statements that might throw an exception whereas catch handles an exception if one exists. The finally can be used for doing any clean up process.
The general form try-catch-finally in C# is shown below:
33 | P a g e
If any exception occurs inside the try block, the control transfers to the appropriate
catch block and later to the finally block.
But in C#, both catch and finally blocks are optional. The try block can exist either
with one or more catch blocks or a finally block or with both catch and finally blocks.
If there is no exception occurred inside the try block, the control directly transfers to
finally block. We can say that the statements inside the finally block is executed always.
Note that it is an error to transfer control out of a finally block by using break, continue,
return or goto.
In C#, exceptions are nothing but objects of the type Exception. The Exception is the
ultimate base class for any exceptions in C#. The C# itself provides couple of standard exceptions. Or even the user can create their own exception classes, provided that this
should inherit from either Exception class or one of the standard derived classes of
Exception class like DivideByZeroExcpetion or ArgumentException etc.
Note: you will learn about base and derived class in the more next chapter.
Exception base class will handle any kind of exceptions type.
4. Exercise
For exercise, you‟ll have to make a program of products registration. The program will
saves maximum 5 products informations. The program will displays the menu. The program will validates the user‟s input must between 1 and 4.
34 | P a g e
If user choose menu 1 then user will be asked several question about new product informations. Each input will be validated.
You can add more products until its reach the maximum amount.
If the product amount has reach its limit then the program will displays “Product is full !”
You can see the list of registered products by choosing menu 2.
35 | P a g e
The program displays the list of regitered products with table view.
The menu 3 will provide you search function by input the keywords. The program searches by product name using the keyword you have inputed.
The result is the first product that start with the keyword.
The last menu is to exit the program.
36 | P a g e
Answer
i. Task 1: Declare necessary variables on the Program class:
j. Task 2: Create input / output to display the menu: You need a variable that holds user‟s choice. And validate the user‟s choice.
k. Task 3: Create a selection that separates processes depend on user‟s choice:
Use switch-case to help make menu.
37 | P a g e
l. Task 4: Create process if the user choose menu Add Product (1):
Validates each user‟s input. If product has reach 5 amount then the program will displays “Product is full !” and go back to menus.
m. Task 5: Create process if the user choose menu View Product (2):
View product displays with table view. You can use the String format to ease you
make a table view.
38 | P a g e
n. Task 6: Create process if the user choose menu Search Product (3): Use Array.Find and Array.IndexOf to create search function on the program. Use
try-catch block to handle wether the data is null (no data found).
o. Task 7: Create process if the user choose menu Exit (4):
The program will ends if user choose menu 4.
39 | P a g e
Chapter 04
Method
40 | P a g e
Method
A method is a code block containing a series of statements. Method is useful
because they allow you to separate your logic into different units. You can pass information to methods, have it perform one or more statements, and retrieve a return
value. The capability to pass parameters and return values is optional and depends on what you want the method to do. A method must be created outside of other methods.
This is the structure for a method :
Access modifiers in C# consist of :
Private Protected
Public Internal
Protected Internal
Access modifiers are optional. You can create a method without access modifier , the default access modifier is Internal.
Return type in C# can be any data types. The value returned from this method can be
used to a variable to use later in the program. A method can only return one value. One of the return type is void which return nothing. Return type other than void must return
something according to the return type. If the return type is int then this method have to return an integer value.
Method name is a unique identifier for what you wish to call this method. A method name can be anything, but you‟d want to name it with a meaningful and associated with
the task this method performed. Method name can be anything that follow the naming rules :
The name must begin with a letter or an underscore & can be followed by a sequence of
letters (A-Z), digits (0-9) or underscore (_)
Special Characters such as ? - * / \\ ! @ # $ % ^ ( ) [ ] { } , ; : . cannot be used in the
method name.
A method name must not be the same as a reserved keyword such as using, public, etc.
The name can contain any number of the allowed characters.
Methods with the same class cannot have the same name
Parameters are used to pass information to this method by the method caller. If you
have more than one parameter to pass to this method, you can seperate the parameters using comma.
Statements are the tasks this method want to perform.
Examples :
<<access modifier>> <<return type>> <<method name>> (<<parameters>>) {
<<statements>>
}
private void printEnter() { Console.WriteLine(“\n”);
}
41 | P a g e
Passing By Reference
The methods that we have created so far use pass by value parameters. This means that a copy of that variable passed to the method is used instead of the actual variables.
If you change the value in this method, that changes won‟t affect the value of the
passed variable outside that method.
There is another way to pass parameter to method, called passing by reference. If you change the value of the passing variable in this method, the value in the calling method
will be changed too. You can use this way by adding keyword “ref” in the parameter, for example:
The following example has a method called AddOne which takes an int as a parameter
and adds 1 to that value. Because it is a reference parameter the original value which in
this case is x will have 1 added to it. It is important to use the ref keyword in both the method that is called and the method that calls that method. You also have to initialize
the variable that is passed by reference to something before passing it.
Recursive Recursive is a function which calls itself iteratively until reaches a stopping point.
private void printEnter(int a) {
for(int i = 0; i < a; i++) { Console.WriteLine(“\n”);
} }
private int add(int a, int b) {
return (a+b); }
42 | P a g e
For Example:
1. Exercise For exercise, you have to make a program about drawing pascal triangle. You
need to create this program by using recursive. The descriptions of the program are : Program begins with asking for number of triangle lines the user wants to display.
You have to make some validations for that input, such as number of triangle lines must be numeric dan between 1 to 10.
After that, this program will print pascal triangle according to the number of
triangle lines inputted by user. If number of triangle lines inputted by user is zero then program will be closed.
Screenshot :
Answer :
First, create the method to print that pascal triangle.
43 | P a g e
Assuming I have this following pascal triangle :
1 1 1
1 x 1 The x value of that pascal triangle is 2, it‟s gotten from the sum of 1 with 1 from the
previous row.
44 | P a g e
Secondly, you will need to call that pascal method.
Note : There are many ways to solve this problem, you can do it your way.
45 | P a g e
Chapter 05
Visual C# .NET Introduction
46 | P a g e
Object Oriented Programming
Object-oriented programming (OOP) tries to alleviate this problem by creating
networks of objects, each like a small software 'machine'. These objects are naturally smaller entities, simplifying the development task of each unit. However, when the
objects co-operate in a system, they become the building blocks of much more complex solution.
There are 3 important concepts about OOP :
Encapsulation Encapsulation, also known as data hiding, is an important object-oriented programming
concept. It is the act of concealing the functionality of a class so that the internal
operations are hidden, and irrelevant, to the programmer. With correct encapsulation, the developer does not need to understand how the class actually
operates in order to communicate with it via its publicly available methods and properties; known as its public interface.
Inheritance
Polymorphism More about inheritance and polymorphism will be discussed later.
The major advantages of OOP are :
simplicity: software objects model real world objects, so the complexity is reduced and the program structure is very clear;
modularity: each object forms a separate entity whose internal workings are decoupled from other parts of the system;
modifiability: it is easy to make minor changes in the data representation or the
procedures in an OO program. Changes inside a class do not affect any other part of a program, since the only public interface that the external world has to a class is
through the use of methods; extensibility: adding new features or responding to changing operating environments
can be solved by introducing a few new objects and modifying some existing ones; maintainability: objects can be maintained separately, making locating and fixing
problems easier; re-usability: objects can be reused in different programs.
Class Definition
Class is a collection of attribute and method that have similar function or a blueprint
from a object. A class usually represent a noun, such as person, place or thing. Rules for naming classes :
A class name must begin with a letter & can be followed by a sequence of letters (A-Z), digits (0-9) or underscore (_)
Special Characters such as ? - + * / \ ! @ # $ % ^ ( ) [ ] { } , ; : . cannot be used in the class name.
A class name must not be the same as a reserved keyword such as using, public, etc.
Access Modifiers
Access Modifiers is used to determine the access of a class or method. Types of access
modifier consists of :
47 | P a g e
This is a class example, a simple program to calculate GPA for students, we can create a
class called „Student‟ which has attributes like nim, name, GPA, and phone number. And one method to calculate GPA like the diagram below :
This diagram, show the structure for class „Student‟
We can implement that diagram into C# program with this code:
Object Definition
An object is a representation from a class. As we already stated above, there are many examples of class or object, for example: your bicycle, your computer, your car, your
48 | P a g e
keyboard. Objects share two characteristics: state and behavior. Bicycles have state
(color, pedal, gear) and behavior (changing gear, applying brakes).
Objects are conceptually similar to real-world object (state and behavior). An object store its state in fields (variable) and exposes its behavior through methods (function).
An object is defined by using keyword “new”.
In the real world, you‟ll find many individual objects all of the same kind. There may be thousands of car in existence, all of the same make and model. Each car was built from
the same set of blueprints and contains the same components. A class is the blueprint
from which individual objects are created.
As we mentioned above, in the real world, you‟ll find many individual objects all of the same kind. Like an university that have thousand of students, all of their students is
have similar attribute, every student must have a nim, name, gpa, and phone number, the students in the university is what we called object from a class, like showed in the
picture above, thomas and claire is a object that represent the class Student.
This following code is a example to make an object from class Student in Java :
Constructor
Each class has its constructor. A constructor is invoked every time an object is
created. Constructor declarations look like method declarations – except that they use
the name of the class and have no return type. Every class may have one or more constructors.
49 | P a g e
Constructor Overloading
You can overload a constructor in C#, that is called constructor overloading.
Overload itself is creating a method with the same name as before, but with the different parameter type or different number of parameters.
In the example above, there are 2 constructor with different parameters.
Operator Overloading Operator overloading permits user-defined operator implementations to be specified
for operations where one or both of the operands are of a user-defined class or struct type.
Operators Overloadability :
Operator Type Operator Overloadable
Binary Operator +, -, *, /, %, &, |, <<, >> Yes
Unary Operator +, -, !, ~, ++, –, true, false Yes
Relational operator ==, !=, <, >, <= , >= Yes, but only as pairs
&&, || No
Conversion Operator () No
Compound
assignment operator
+=, -=, *=, /=, %= Yes, automatically
overloaded when the respective
50 | P a g e
binary operator is
overloaded.
=, . , ?:, ->, new, is, as, size of
No
Inheritance
Inheritance is one of the object oriented programming concept. Inheritance allows
you to reuse existing code. C# does not support multiple inheritance. It only can be
derived from one parent. When you are using inheritance, there is one thing you need to remember, which is constructor from the parent class always invoked first before the
child class is invoked. There are two important points about inheritance :
Base class is the parent class. Derived class is the child from parent. Derived class inherits attributes and
behaviours(methods) from the base class.
This is an inheritance example The base class from the example above is “ParentClass”.
The derived class from the example above is “ChildClass”. The output of the example above is :
Abstract Class
Abstract class is like an ordinary class, except the fact that abstract class can not be used to create an object. Abstract class is created to be used in inheritance. In this
abstract class you can create attributes, methods, and abstract methods.
Parent Constructor.
Child Constructor.
I‟m a Parent Class.
51 | P a g e
Abstract method is also like an ordinary methode, except the fact that abstract
method must be overriden in the derived class. Overriding methods must have the same signature, name and parameters, as the virtual base class method it is overriding.
In this example, there is an abstract class called “Shape”. This class has 2 attributes
which are width and height and 1 abstract method called calculateArea().
This example above is the example of abstract class implementation. In this example, “Rectangle” is inherited from abstract class “Shape”. In “Shape”, there is an abstract
method called calculateArea(), so the inherited class “Rectangle” must also has an
method called calculateArea() and has a keyword override in that method, this is called overriding.
Polymorphism
Polymorphism comes from the Greek words of poly and morphos. Polymorphism means many forms. You can implement polymorphism with this ways :
Create a virtual method in base class (parent class) Create a derived class which contains methods with keyword override.
For Example :
52 | P a g e
In the code above, Rectangle and Triangle is inheritted from Shape. calculateArea() is an example of overriding method.
2. Exercise
Mbadogz want to teach his sister about calculating tube, cone, and ball volumes. In order to help his sister to make sure that she has the right calculations, Mbadogz try to
create a program to do that calculations. You need to help Mbadogz to create this
program using object oriented concepts. This program consists of 4 choices :
If user chooses Tube then user will be asked to input radius and height of that tube. Radius and height for this tube must between 1 and 100. After user has inputted the
53 | P a g e
right value of radius and height, program will show the volume of that object. You
can calculate the volume of tube using :
If user chooses Cone then user will be asked to input raidus and height of that cone.
Radius and height of this cone must also between 1 and 100. After user has inputted the right value of radius and height, program will show the volume of that object.
You can calculate the volume of cone using :
If user chooses Ball then user will be asked to input radius of that ball. Radius of this
ball must between 1 and 100. After user has inputted the right value of radius, program will show the volume of that ball. You can calculate the volume of ball
using:
The value of dari is
If user chooses to exit then program will be closed.
Answer
To solve this problem, you need to design classes you will be used first.
First, I‟d create class Shape, this Shape class will contain r which is radius. Every shape that contain circle form, like tube, cone, ball must have a radius. So I decide to put this
radius in Shape class which will be the super class.
Tube is a subclass. It‟s inheritted from Shape. And because of this reason,
Tube has 2 attributes which are „r‟ and „t‟. „r‟ is inheritted from Shape.
54 | P a g e
Cone is also a subclass. It‟s inheritted
from Shape. And because of this reason, Cone has 2 attributes which
are „r‟ and „t‟. „r‟ is inheritted from Shape.
Ball is also a subclass. It‟s inheritted from Shape. And because of this reason,
Ball has only 1 attribute „r‟ which is inheritted from Shape class.
This method is used to do the
validation for radius and height.
55 | P a g e
56 | P a g e
Note : There are many ways to solve this problem, you can do it your way.
57 | P a g e
Chapter 06
Graphical user Interface Basic
58 | P a g e
Graphical User Interface (GUI) represents the information and actions available to a
user through graphical icons and visual indicators such as secondary notation, as opposed to text-based interfaces, typed command labels or text navigation.
Every component in GUI have its own properties and events.
Windows Form
To create a windows form application, you must choose Windows Form Application project type. When windows form application successfully created, you will see this form
below. Form is used to place components like label, button, textbox, etc.
You can change the title, icon, size, location and many other things of that form. You
can change all of that through properties tab.
59 | P a g e
Properties Tab Interface
You can change the title of form by changing Text property, change the background
color of form by changing BackColor property, and many other properties you can
change to create a form as you‟d like to.
Form also has events which will be invoked when the specified event occured.
60 | P a g e
Events of Form
You can use these events by double clicking on the events you want.
For Example :
61 | P a g e
MDI Form and MenuStrip
MDI stands for Multiple document interface. You can add many other forms in MDIForm
which are called MDI Child, so you can do many things simultaneously.
MenuStrip is used to display menus in MDI Form. You can find it in the toolbox.
You can create MDI form by adding new item and choosing MDI Parent Form.
There is another way to create MDI Form. Which is : Create a normal form application
Change IsMDIContainer property of that form to TRUE. When you change this
property, that form will be a MDI Form.
How to create a MDI Child : Create another form that will be used as MDI Child.
In MDI Parent which is the MDI Form, create the following code :
62 | P a g e
The result is :
Show MDI Child in the screenshoot above is a menu in MenuStrip.
Label, LinkLabel and PictureBox Label is one of windows components which is used to display an uneditable text.
LinkLabel is used to display an uneditable text and to give a hyperlink to the text.
PictureBox is used to display an image.
63 | P a g e
The form above, has a label with text “This is a Label” and a PictureBox. You can also
change font size and font type for label with Font property. There are many other
properties you can use to make label looks better. To change the text of label, you can find Text property in properties and change it.
To give hyperlink to the text, you have to generate a click event to the linklabel.
To change the image of PictureBox, you can click on the Choose Image link in the form
above. You can also change the size mode of that PictureBox. If you want the size of image depends on you, you can change that size mode to
stretch image. If you want the size of the image has same width and height with the
actual image, you can change size mode to Auto Fit. There are 3 other modes for image, which are Normal, Center image, and Zoom. The default mode of an image is
Normal.
You can also change the properties of components through code. To change the property of a component through code, you must give a name to the component you want to
change. You can give name for that component through property Name. After that, you can change the property through code. For example I have an interface like the
screenshoot above, I want to change the text to “I‟m changing..” to the label with text
“This is a Label”.
64 | P a g e
TextBox and MaskedTextBox
TextBox is one of GUI components. It‟s used to create an editable text. MaskedTextBox is also an editable text. MaskedTextBox is like a TextBox which can
mask the Date, IP Address, SSN, Phone numbers, digits, decimal and checks the validation, and automatically set the delimiter location. You can also use MaskedTextBox
for validation, for example to validate user‟s input have to be numeric, and other
validations.
You can set the mask for MaskedTextBox by clicking on the Set Mask link. After that, it will show a window like the image below to choose what kind of mask wanted to be
used.
65 | P a g e
RadioButton and GroupBox RadioButton is used to display options you have. You can only choose one option in
RadioButton.
GroupBox is used to categorize options you have which you want to implement it with RadioButton.
In the example above, Male and Female are RadioButton and in GroupBox Gender. While SMA, S1, S2, and S3 are RadioButton and in GroupBox Last Education.
CheckBox and CheckedListBox
CheckBox is used to display options you have. The only thing different from RadioButton is in CheckBox you can choose one or many options in one group.
CheckedListBox is similar to CheckBox. It‟s like many CheckBoxs put in a list.
66 | P a g e
3. Exercise
An organization called Bluejack want to create a program to help their new member registration.
Screenshots :
Main Form :
This form consists of 2 menu : Registration Form and About.
When you click on menu Registration Form : form Registration will be showed. When you click on menu About : form About will be showed.
67 | P a g e
Registration Form :
Registration Form consists of : Label for text “Full Name”, “Birth Date”, “Gender”, and “Skills”
TextBox for “Full Name” MaskedTextBox for “Birth Date”
GroupBox for gender RadioButton for “Male” and “Female”
CheckedListBox for “Skills”
You have to do the following validation when user clicks on submit :
Full name must be filled Gender must be chosen
At least 1 skill must be chosen
When user clicks on Reset, reset all components to default.
68 | P a g e
About Form :
This form consists of : PictureBox for image
Label for text
Answer To solve this problem, you need to :
1. Create 3 forms, set one of those forms‟ IsMDIContainer property to TRUE. 2. Create components for those 3 forms.
3. In order to show Registration Form when user clicks on menu Registration Form
and show About Form when user clicks on menu About, you need to create the following code in Main Form :
69 | P a g e
4. To do validation in Registration Form, you need to do the following code in Registration Form:
70 | P a g e
Chapter 07
Graphical User Interface Intermediate
71 | P a g e
ComboBox
ComboBox combines TextBox features with a drop-down list. A drop-down list is a GUI component that contains a list from which values can be chosen.
You can change combobox style with DropDownStyle property.
Assuming a scenario, if I click on the Submit button, it will show the selected item in the checkbox. Then, you‟d have to do the following code :
ListBox
ListBox is the same with ComboBox. The only thing different is in ListBox you can select many items. To create a list with multi selection capability, you must change
SelectionMode property to MultiSimple or MultiExtended.
72 | P a g e
Assuming a scenario, I want to display selected items in ListBox by using MessageBox when Submit Button is clicked. I‟d have to create the following code :
The result :
This messagebox appeared after button Submit is clicked
73 | P a g e
DateTimePicker DateTimePicker is one of GUI component. It‟s used to choose date in form. Its form like
a common ComboBox, but after you click at the DateTimePicker, it will show a calendar for you to pick.
To get selected date in the DateTimePicker, you can create the following code :
MonthCalendar
MonthCalendar is used to choose date whether it‟s for birth day, meeting date, etc.
74 | P a g e
To get selected date, you can create the following code :
ListView
ListView is used to show a list of data with image and text in it. You can select many items in one ListView.
To use this ListView which contains image, you must create ImageList component first.
To set images for ImageList you can click on the Choose images link in the picture above and it will show this window below :
To add new image, you can click on the Add button. To remove existing image, choose
the image and click the Remove button.
75 | P a g e
After creating ImageList, you can start to input items in the ListView.
First, choose the Small ImageList and LargeImageList to the name of ImageList you created before.
Second, you can add new item with clicking on the Edit Items link. It will show this window below :
To add new item, click Add. After that, change the text for the new item, and choose the
ImageIndex property, in ImageIndex, you will see the images you have added to the ImageList.
76 | P a g e
TreeView TreeView is used to display menu or data in tree view.
To add new item or data you can click on Edit Nodes link and display this window below.
77 | P a g e
Add Root is used to add new root. Add Child is used to add new child in an existing
root.
To know selected item, you can create the following code :
ProgressBar
ProgressBar is used to show the progress of a task, such as a download or file transfer. The important properties in ProgressBar :
Minimum Minimum value of the ProgressBar
Maximum Maximum value of the ProgressBar, the ProgressBar will stop loading if it reaches this maximum value.
To use ProgressBar, you need to create a Timer first. Timer is used to refresh application after interval second. In Timer properties, set the interval to whatever you want. If
interval is 1000, it means 1 second.
Assuming the scenario, if user clicks on the Submit button, ProgressBar will start
loading till the loading complete. You can do the following code :
78 | P a g e
79 | P a g e
4. Exercise For exercise, create a form with components like the picture below.
Do the following action in that form :
When you click on the treeview node, the picture in the PictureBox will be changed according to what movie‟s title is chosen.
When Add To Cart is clicked, add the selected tree node and picture to ListView. When Remove is clicked, remove the selected item in ListView. If there is no item
selected, show some error message.
80 | P a g e
Answer Create a form with components likes the screenshot above.
The items in TreeView must have the same name with the name of image which wants to be showed in PictureBox.
Create the following code :
81 | P a g e
82 | P a g e
Chapter 08
Graphical User Interface Advanced
83 | P a g e
DataGridView
DataGridView is used to display data from your database or other data source in table‟s form.
Enable Adding Can add content in table directly
Enable Editting Can edit content in table directly
Enable Deleting Can delete content in table directly
Enable Column Can change the column order in table
To add columns to DataGridView, you can create the following code :
To add new row to DataGridView, you can create the following code :
To update data in DataGridView, you can create the following code :
To delete data row in DataGridView, you can create the following code :
84 | P a g e
Result :
DataSet
1. Make a new Database
1. In Solution Explorer, right click on your project name, choose Add then New Item.,
85 | P a g e
86 | P a g e
2. Choose Service-based Database (*.mdf)
87 | P a g e
3. After that, in your Server Explorer will show one file named [database name].mdf, double click on it and it will show Database Explorer.
88 | P a g e
4. In Server Explorer, right click on Table, choose Add New Table
89 | P a g e
5. Determine which columns you want to add to the new table including their data types.
6. After finishing determine your columns in that table, save the table first (you can do it with Ctrl + S)
90 | P a g e
7. In Database Explorer, right click on the table name you‟ve created, choose Show Table Data to edit your data in that table.
8. Input your data according to the column name you‟ve decided
9.
2. Make a DataSet
1. First , drag a dataset from toolbox to your form , then it will display a dialog like
this , choose your database , and OK
91 | P a g e
2. Back to solution explorer , choose your dataset (in this case , our dataset‟s name
is Database1DataSet1.xsd)
3. Drag your table from server explorer -> tables , then your table‟s name and field
will display in your dataset
92 | P a g e
4. After all , compile or run your program (F5 or CTRL + F5) , then close it and back
to ToolBox , you will see a new group before All Windows Forms , it is your
dataset‟s data components
5. Drag your table‟s table adapter / [tablename]TableAdapter to your form
93 | P a g e
6. Add new datagridview to your form , choose option (the small triangle in top
right) , then in „Choose Data Source‟ , choose other data sources -> project data
sources -> [dataset_name] -> [table_name]
7. Fill your table adapter with data from dataset . Add event when your form was
loaded , by double click the form‟s name and create the following code
94 | P a g e
8. Run your program (F5 or CTRL + F5) , and the datagridview will display all data
in MsStudent
95 | P a g e
Data Navigator
Data Navigator is used to navigate data from your database what is displayed in
datagridview
1. In this tutorial , you must make a dataset before . First , drag bindingNavigator from
toolbox to your form
2. Add event when your form was loaded , by double click the form‟s name and append
a code for add a binding navigator to binding source
3. Run your program (F5 or CTRL + F5) , now you can navigate your data with prev / next / first / last button
Binding navigator‟s button and its function
Icon Function
Go to first data
Go to previous data
Go to next data
Go to last data
Add new Row
Delete Current Row
96 | P a g e
5. Exercise
Do the following action in that form 1. When you click „Insert‟ , textbox movie , genre , and rating will be enabled and
button delete will be disabled
2. When you click „Insert‟ again , then all data in textbox movie , genre and rating will
be inserted into datagridview and button delete will be enabled
3. When you click „Delete‟ , then a message box will display and ask you „Are you sure
?‟ , if you choose „Yes‟ , then the data in row that you select will be remove
4. If you click the row in datagridview , data in textbox movie , genre , and rating will
adjust with data in datagridview that you select
97 | P a g e
Answer
Create a form with components like the screenshot above. Don‟t forget to change your object‟s name . In this case , we change our object‟s name like
this Button : btnDelete , btnInsert
Textbox : txtMovie , txtGenre , txtRating
For event , we will use Button insert : Click
Button delete : Click
DataGridView : Cell Click
Create the following code :
98 | P a g e
99 | P a g e
Chapter 09
Database Application
100 | P a g e
Database
Database is used to store large data. Database can be defined by a set of columns and rows. There are many kinds of database, such as Access database, SQL Database,
MySQL database, Oracle Database, DB2, etc.
There are many ways to create an application with database. In this tutorial, I‟ll use Service-based Database (*.mdb).
SQL (Structured Query Language)
Based on its function, it‟s divided into 3 parts :
DDL (Data Definition Language) It‟s used to define data.
DDL consists of CREATE, ALTER, and DROP DML (Data Manipulation Language)
It‟s used to manipulate data. DDL consists of SELECT, INSERT, UPDATE, and DELETE
DCL (Data Control Language) It‟s used to control database access right.
DCL consists of GRANT, REVOKE, COMMIT, ROLLBACK
In this tutorial, we will discuss about DML.
Connect to Database
Steps to connect to Database : 1. In Solution Explorer, right click on your project name, choose Add then New
Item.
101 | P a g e
1. Choose Service-based Database (*.mdf)
2. After that, in your Solution Explorer will show one file named [database name].mdf, double click on it and it will show Database Explorer.
3. In Server Explorer, right click on Table, choose Add New Table
102 | P a g e
4. Determine which columns you want to add to the new table including their
data types.
Don‟t forget to set primary key for that table, such as EmployeeID.
5. After finishing determine your columns in that table, save the table first
(you can do it with Ctrl + S)
6. In Server Explorer, right click on the table name you‟ve created, choose
Show Table Data to edit your data in that table.
103 | P a g e
7. Input your data according to the column name you‟ve decided.
8. Your database is ready to be used. 2. Right click on your project name in Solution Explorer and choose Add then New
Item.
1. Choose ADO .NET Entity Data Model, input file name and click Add.
104 | P a g e
2. Now , we can do all our query using LINQ. What is LINQ ? LINQ is a
programming model that introduces queries as a first-class concept into any Microsoft .NET language. However, complete support for LINQ requires some
extensions in the language used. These extensions boost productivity, thereby
providing a shorter, meaningful, and expressive syntax to manipulate data.
LINQ vs SQL Query
Select Insert Update Delete
LINQ From obj in
Employee
select obj
Employee emp = new
Employee {EmployeeID
= „EM001‟ ,
EmployeeName = „Garry‟
, Salary = 10000
};
Employee emp = (from obj
in MsEmployee where
obj.EmployeeID.Equals('EM
001') select obj).First()
Emp.EmployeeName =
„Hero‟;
Data_obj.SubmitChanges();
Employee emp = (from obj in
Employee where
obj.EmployeeID.Equals('EM0
01') select obj).First()
Data_obj.Employee.DeleteOn
Submit(emp);
Data_obj.SubmitChanges();
SQL Select * from
Employee
Insert into Employee
values
(„ID‟,‟Name‟,‟Salary‟)
Update Employee set
ID=‟EM005‟ where
Name=‟Admin‟
Delete from Employee where
ID =‟EM001‟
105 | P a g e
View Database in DataGridView
To view data in DataGridView, you must first do all the steps in connect to database. After that, you also need to create one DataGridView in your form.
After that, you just need to create the following code :
The result :
106 | P a g e
Another example :
The result :
ORDER BY Order By is used when you want to sort data ascending or descending.
107 | P a g e
Aggregate
Insert Data
108 | P a g e
Update Data
Delete Data
109 | P a g e
2. Exercise
For exercise, you need to create a form like this screenshot below :
1. If user changes genre in ComboBox, the price and table contents will be
regenerated from database according to the selected genre. 2. If user clicks on comics table, the text in TextBox, ComboBox, and
MaskedTextBox will be changed. 3. If user wants to insert new data to MsComic, user can input the new data to
TextBox, ComboBox, and MaskedTextBox and click INSERT button. 4. If user wants to update data in MsComic, user can first choose the row wants to
be updated, and then input updated data to TextBox, ComboBox, and
MaskedTextBox and click UPDATE Button. 5. If user wants to delete data in MsComic, user can fist choose the row wants to be
deleted, and then click on DELETE Button. There are data like :
MsComicGenre
110 | P a g e
MsComic
Answer
To solve this problem, you have to do the following steps : Create a form with components according to the screenshot above.
Add -> New Item -> Service-based-Database Create 2 tables with structures like screenshot above.
Insert some random data to that 2 tables. Add -> New Item -> ADO.Net Entity Data Model
Do the following code :
Database1 in Database1Entities1 is the name of the database. index will be used to save the selected row index of Master Comic Table
This method will be used to load all genres in MsGenre and put it in ComboBox.
This method is used to load all comic data with the specific genre in MsComic and put it in table Comic. ComicGridView is the name of the DataGridView.
111 | P a g e
This method is used to reload table and price data according to the selected item in ComboBox.
This method is used to load data in TextBox, ComboBox, MaskedTextBox according to
the selected data row in Comic Table. In my Comic table, I have 4 columns, consists of : ComicID, Name, Author,
TotalChapter. ComicID is in cell with index = 0
Name is in cell with index = 1
Author is in cell with index = 2 TotalChapter is in cell with index = 3
“ComicGridView.Rows[index].Cells[1] .Value” means I want to get data from cell with index = 1 which is Name in the selected row.
This method is constructor of Form1. This method will be automatically called when you
create an object from this Form1. In this method, I tried to get the genreID according to the selected item in ComboBox, and then called loadComic and loadText method.
112 | P a g e
This method is called when user clicks on DELETE Button.
In this method, I tried to get ComicID which is selected by user in Comic table.
After that, I get the object with that id, and then delete it. After I delete that object, I call method refresh to refresh the data in Comic table.
This method is called when user clicks on Comic table. When user clicks on table, index will be changed to the selected row. After that, reload all data in TextBox, ComboBox,
and MaskedTextBox.
This method is called when user clicks on INSERT Button. To insert new object to MsComic, first you need to create new object from class
MsComic, and then set the value for all attributes in that class.
113 | P a g e
This method is called when user clicks on UPDATE Button. To update an existing object, you need to get the object you want to be changed first,
and then you can that attribute directly.
This method is called when user changes the genre type in ComboBox. When this method is called, program will call refresh method.
114 | P a g e
Chapter 10
Visual C# .NET Introduction
Report
Report is a piece of information describing, or an account of certain events given or presented to someone.
Written reports are documents which present focused, salient content to a specific
audience. Reports are often used to display the result of an experiment, investigation, or inquiry. The audience may be public or private, an individual or the public in general.
Reports are used in government, business, education, science, and other fields.
Reports often use persuasive elements, such as graphics, images, voice, or
specialized vocabulary in order to persuade that specific audience to undertake an action. One of the most common formats for presenting reports is IMRAD: Introduction, Methods,
Results and Discussion. This structure is standard for the genre because it mirrors the traditional publication of scientific research and summons the ethos and credibility of that
discipline. Reports are not required to follow this pattern, and may use alternative patterns like the problem-solution format.
Additional elements often used to persuade readers include: headings to indicate topics, to more complex formats including charts, tables, figures, pictures, tables of
contents, abstracts, summaries, appendices, footnotes, hyperlinks, and references.
Some examples of reports are: scientific reports, recommendation reports, white papers, annual reports, auditor's reports, workplace reports, cencus reports, trip reports,
progress reports, investigative reports, budget reports, policy reports, demographic reports, credit reports, appraisal reports, inspection reports, military reports, bound reports, etc.
115 | P a g e
Crystal Report
Crystal Reports is a business intelligence application used to design and generate
reports from a wide range of data sources. Several other applications, including Microsoft Visual Studio, at one time bundled an OEM version of Crystal Reports as a general purpose
reporting tool. Crystal Reports is a popular report writer, especially so when Microsoft bundled it with Visual Studio versions 2003 through 2008. Microsoft discontinued this
practice and later released their own competitive reporting tool, SQL Server Reporting Services (SSRS). Crystal Reports for Visual Studio 2010 is still available as add-on software.
6. Tutorial
Prepare data source
For generating Crystal Reports from C#, you need to connect a database and some tables with data. In the following section you can see how to create a sample Database and
Tables and the data. Use SQL Server 2008 as the DBMS.
First you have to create a database named it as crystaldb. In the crystaldb database,
create three tables. The Table Structure follows:
Tables Columns
products product_id
product_name
product_price
orders order_id
order_date
order_customer
order_employee
order_details order_id
product_id
product_qty
curr_price
SQL command for creating tables are follows:
116 | P a g e
Enter some data to the tables:
From the following pictures you can see some data in the table for C# - Crystal Report.
PRODUCTS
ORDERS
117 | P a g e
ORDER_DETAILS
Crystal Report Step by Step
You are going to create a new Crystal Reports in C# from products table in the above mentioned database crystaldb. The Product Table has three fields (product_id,
product_name, product_price) and you are showing the whole data from products table to the C# - Crystal Reports project.
Open Visual Studio .NET and select a new CSharp Windows project.
118 | P a g e
Now you will get the default Form1.cs. From the main menu in Visual Studio C# project
select project Add New Item . Then Add New Item dialogue will appear and select Crystal
Reports from the dialogue box.
119 | P a g e
Select Report type from Crystal Reports gallery.
Accept the default settings and click OK.
Next step is to select the appropriate connection to your database (here crystaldb). Here
you are going to select OLEDB Connection for SQL Server to connect Crystal Reports in C#.
Select OLE DB (ADO) from Create New Connection.
120 | P a g e
Select Microsoft OLE DB Provider for SQL Server.
121 | P a g e
The next screen is the SQL Server authentication screen for connecting to the database -
crystaldb. Select your Sql Server name , enter userid , password and select your Database Name.
122 | P a g e
After you click the finish button , the next window you will get your Server name under
OLEDB Connection, from there selected database name (crystaldb) and click the tables , then you can see all your tables from your database.
From the tables list double click the products table then you can see the sproduct table will
come in the right side list.
123 | P a g e
Click Next Button
Select all fields from products table to the right side list.
124 | P a g e
Click Finish Button. Then you can see the Crystal Reports designer window in your C#
project. In the Crystal Reports designer window you can see the selected fields from products table. You can arrange the field Objects and design of the screen according your
requirements. After that your screen is look like the following picture.
Now the designing part is over and the next step is to call the Crystal Reports in your C# application and view it through Crystal Reports Viewer control in C#.
125 | P a g e
Select the default form (Form1.cs) you created in C# and drag a button and a
CrystalReportViewer control to your form .
Go to the source code view and inside the default constructor block follow the code below.
When you run the source code you will get the report like the following picture.
126 | P a g e
Crystal Reports from multiple tables
Here you are going to generate Crystal Reports from multiple tables in C#. Here you have three tables (orders, order_details, and products ) and you are generating a Crystal
Report from these three tables by connecting each table with their related fields.
Create new CrystalReport. Select all tables from the table list to right side list box,
because you are creating report from three tables ( orders, order_details, products).
127 | P a g e
The next step is to make relations between these selected tables. Here you are connecting
the related fields from each table. For that you arrange the tables in visible area in the list (this is not necessary ) and select the fields that you want to make relation and drag to the
related field of the other selected tables. After made the relations with tables the screen is look like the following picture.
128 | P a g e
Next step is to select the fields from the selected tables (orders, order_details, products).
Here you are selecting the fields order_customer , order_date from orders , product_name from products and product_qty from order_details. The field selection screen is look like the
following picture.
129 | P a g e
You will make the report is grouping by order_customer. After click the Next button. Make
the order_customer and order_date to Group By fields:
130 | P a g e
After select the fields from tables, click the Finish button because now you are not using any
other functionalities of the Crystal Reports wizard. After that you will get the Crystal Reports designer window . You can arrange the fields in the designer window according to your
requirement to view the report.
For re-arranging fields in the designer window , you can drag the field object on the screen . For editing right click the field object and select Edit Text Object. The following picture
shows the sample of designer window after rearrange the field.
131 | P a g e
Now the designing part is over and the next step is to call the Crystal Reports in C# and
view it in Crystal Reports Viewer control.
Select the default form (Form1.cs) you created in C# and change the code as the following picture.
After you run the source code you will get the report like this.
132 | P a g e
Formula & Summary Fields
If you have a Crystal Reports with Qty and Price fields and you need an additional
field in your Crystal Reports for Total, that is TOTAL = QTY X PRICE. In these types of
situations you can use the Formula Field in Crystal Reports.
Create a new Crystal Reports with fields order_customer, order_date, product_name, product_qty, and curr_price. In that report selecting only five fields , here you need formula
field Total.
Next step is to create a Formula Field for showing the result of Qty X Price .
Right Click the Formula Field in the Field Explorer and click New. Then you will get an Input Message Box, type Total in textbox and click Use Editor.
133 | P a g e
Now you can see the Formula Editor screen . Here you can enter which formula you want. Here we want the result of Qty X Price . For that we select order_details.product_qty, the
multipy operator (*), and order_details.curr_price. Double click each field for selection.
Now you can see Total Under the Formula Field . Drag the field in to the Crystal Reports where you want to display Total.
Next you will make a summary field for Grand Total in the end of the report. In the Crystal Reports designer view window, right click on the Report Footer , just below the Total field
and select Insert -> Summary.
134 | P a g e
Then you will get a screen , select the Total from the combo box and select Sum from next Combo Box, and summary location Grand Total (Report Footer) . Click Ok button
135 | P a g e
Now you can see Sum of @Total is just below the Total field in the report Footer.
You may want to give it a label. Just beside the Sum of @Total field and select Insert ->
Text Object.
Put it next to Sum of @Total.
Now the designing part is over and the next step is to call the Crystal Reports in C# and
view it in Crystal Reports Viewer control.
Select the default form (Form1.cs) you created in C# and change the code as the following
picture.
136 | P a g e
When you run this program your screen will look like the following picture.
Crystal Report with Parameter
Create a new Crystal Reports with fields order_customer, order_date, product_name, product_qty, and curr_price.
To make parameter fields, on the Field Explorer right click on Parameter Field node
and choose New.
Here you will make a parameter that restrict report based on date. So you will make two parameters (DateFrom and DateTo)
137 | P a g e
DateFrom parameter:
138 | P a g e
DateTo:
And Parameter Fields node will has two new child.
After creating the parameter field , we have to create the selection formula for the Crystal
Reports parameter. For creating selection formula, Right click on Crystal Reports designer
window , select REPORT SELECTION FORMULA RECORD.
The following picture shows how to select the fields from formula editor and make the formula. Double click each field then it will automatically selected.
139 | P a g e
After the creation of selection formula you can close that screen.
Now the designing part is over and the next step is to call the Crystal Reports in C# and
view it in Crystal Reports Viewer control.
Select the default form (Form1.cs) you created in CSharp and drag two datepickers (from
date entry and to date entry), a button and CrystalReportViewer control to your form.
Add a click event to Show Report button. Go to source code view. Import CrystalDecisions.CrystalReports.Engine and CrystalDecisions.Shared.
140 | P a g e
Make the default constructor as follows.
Copy and paste the following source code to your event click function: private void button1_Click(object sender, EventArgs e) {
ReportDocument cryRpt = new ReportDocument(); cryRpt.Load("<YOUR PATH>\CrystalReport4.rpt"); TableLogOnInfos crtableLogoninfos = new TableLogOnInfos(); TableLogOnInfo crtableLogoninfo = new TableLogOnInfo(); ConnectionInfo crConnectionInfo = new ConnectionInfo(); Tables CrTables; ParameterFieldDefinitions crParameterFieldDefinitions ; ParameterFieldDefinition crParameterFieldDefinition ; ParameterValues crParameterValues = new ParameterValues(); ParameterDiscreteValue crParameterDiscreteValue = new ParameterDiscreteValue(); crParameterDiscreteValue.Value = dateTimePicker1.Value.ToString("yyyy-MM-dd"); crParameterFieldDefinitions = cryRpt.DataDefinition.ParameterFields; crParameterFieldDefinition = crParameterFieldDefinitions["DateFrom"]; crParameterValues = crParameterFieldDefinition.CurrentValues; crParameterValues.Clear(); crParameterValues.Add(crParameterDiscreteValue); crParameterFieldDefinition.ApplyCurrentValues(crParameterValues); crParameterDiscreteValue.Value = dateTimePicker2.Value.ToString("yyyy-MM-dd"); crParameterFieldDefinitions = cryRpt.DataDefinition.ParameterFields; crParameterFieldDefinition = crParameterFieldDefinitions["DateTo"]; crParameterValues = crParameterFieldDefinition.CurrentValues; crParameterValues.Add(crParameterDiscreteValue); crParameterFieldDefinition.ApplyCurrentValues(crParameterValues); crConnectionInfo.ServerName = "<SERVERNAME>"; crConnectionInfo.DatabaseName = "<DBNAME>"; crConnectionInfo.UserID = "<USERID>"; crConnectionInfo.Password = "<PASSWORD>"; CrTables = cryRpt.Database.Tables; foreach (CrystalDecisions.CrystalReports.Engine.Table CrTable in CrTables) {
crtableLogoninfo = CrTable.LogOnInfo; crtableLogoninfo.ConnectionInfo = crConnectionInfo; CrTable.ApplyLogOnInfo(crtableLogoninfo);
} crystalReportViewer1.ReportSource = cryRpt; crystalReportViewer1.Refresh();
}
141 | P a g e
Now you can run the program . Enter from date and to date , then you can see the report
whose order date is between from date and to date you passed to Crystal reports.
142 | P a g e
Chapter 11
Character, String, and Regular Expression
143 | P a g e
String Properties
Properties provide the opportunity to protect a field in a class by reading and writing
to it through the property. In other languages, this is often accomplished by programs implementing specialized getter and setter methods. C# properties enable this type of
protection while also letting you access the property just like it was a field.
Another benefit of properties over fields is that you can change their internal implementation over time. With a public field, the underlying data type must always be the
same because calling code depends on the field being the same. However, with a property, you can change the implementation. For example, if a customer has an ID that is originally
stored as an int, you might have a requirements change that made you perform a validation to ensure that calling code could never set the ID to a negative value. If it was a field, you
would never be able to do this, but a property allows you to make such a change without breaking code. Now, lets see how to use properties.
String Indexer
Defining an indexer allows you to create classes that act like "virtual arrays."
Instances of that class can be accessed using the [] array access operator. Defining an indexer in C# is similar to defining operator [] in C++, but is considerably more flexible. For
classes that encapsulate array or collection like functionality, using an indexer allows the users of that class to use the array syntax to access the class.
144 | P a g e
Comparison String
a. Equality and Inequality Operators
In an earlier chapter we discussed the equality (==) and inequality (!=) conditional / relational operators. These operators allow an exact, case-sensitive comparison of
two strings. In the case of the equality operator, if the strings match, the resultant Boolean value is true. If they are different the result is false. The inequality operator
returns the opposite result, as shown below:
These operators are useful but have limitations. They do not allow you to consider
the equality of two strings that match in all but capitalisation or other cultural factors. Nor do they allow you to determine that one string is greater than another.
This article explains the methods that are provided to solve these problems.
145 | P a g e
b. CompareTo Method
The .NET framework provides a method named CompareTo for many data types,
including strings. It allows two values to be compared and returns a result that
indicates not only if they are equal but also which is the greater when they are not. The method considers cultural information when comparing strings. For example,
Japanese katakana characters can be written in two ways, half-width or full-width. The CompareTo method considers characters written as full-width to be equal to the
same half-width characters. The same cultural information is used to determine which string is the greater.
The CompareTo method operates against an existing string. The string that it is to be
compared with is passed to a parameter. The method returns an integer indicating
the result of the comparison as follows:
Return Value Meaning
0 The strings are equal.
< 0 The first string is less than the second.
> 0 The first string is greater than the second or the second string is
null.
This can be clarified with an example:
c. Compare Method
The Compare function is a static method of the string class. It provides similar
functionality to CompareTo but allows more options to be specified. As a static member
of the string class, both strings are passed as parameters.
The CompareTo method raises an exception if the string that is being tested is null
because a null object has no available methods. However, as the Compare method is
static, null strings can be compared.
146 | P a g e
The Compare method allows toy to decide whether to perform case-sensitive or case-
insensitive comparisons. The differentiation between upper case and lower case
lettering is applied according to the user's language settings. To determine whether
to use case-sensitive comparison a third, Boolean parameter is used. If the value is
true, character casing is ignored. If false, the effect is the same as not supplying the parameter at all; the test is case-sensitive.
d. CompareOrdinal Method
The CompareOrdinal static method allows case-sensitive comparison of two strings.
It differs from Compare in that the comparison result is based upon the numeric
Unicode values for each character. As the importance of characters in a cultural
context can be different to the fixed numeric ordering of Unicode, different results
may occur when comparing using this method.
e. Equals Method
The Equals method is included for completeness. It returns a Boolean result indicating
if two strings match, similar to the equality operator (==). The method can be used
against a string object with a single parameter or as a static member with two
parameters for the strings to be compared.
Char Methods
The following table explains some of Char static methods:
Name Return Type Notes
IsDigit(Char) bool Indicates whether the specified Unicode character is categorized as a decimal digit.
IsLetter(Char) bool Indicates whether the specified Unicode character
is categorized as a Unicode letter.
147 | P a g e
IsLetterOrDigit(Char) bool Indicates whether the specified Unicode character is categorized as a letter or a decimal digit.
IsLower(Char) bool Indicates whether the specified Unicode character
is categorized as a lowercase letter.
IsNumber(Char) bool Indicates whether the specified Unicode character
is categorized as a number.
IsPunctuation(Char) bool Indicates whether the specified Unicode character
is categorized as a punctuation mark.
IsSeparator(Char) bool Indicates whether the specified Unicode character is categorized as a separator character.
IsSymbol(Char) bool Indicates whether the specified Unicode character is categorized as a symbol character.
IsUpper(Char) bool Indicates whether the specified Unicode character
is categorized as an uppercase letter.
IsWhiteSpace(Char) bool Indicates whether the specified Unicode character
is categorized as white space.
ToLower(Char) char Converts the value of a Unicode character to its lowercase equivalent.
ToUpper(Char) char Converts the value of a Unicode character to its uppercase equivalent.
Example C# code:
148 | P a g e
And see the result.
Regular Expression
Regular Expressions are a powerful pattern matching language that is part of many
modern programming languages. Regular Expressions allow you to apply a pattern to an input string and return a list of the matches within the text. Regular expressions also allow
text to be replaced using replacement patterns. It is a very powerful version of find and replace.
Microsoft's .NET Framework contains a set of classes for working with Regular Expressions in the System.Text.RegularExpressions namespace
In literal C# strings, as well as in C++ and many other .NET languages, the
backslash is an escape character. The literal string "\\" is a single backslash. In regular
expressions, the backslash is also an escape character. The regular expression \\ matches a
single backslash. This regular expression as a C# string, becomes "\\\\". That's right: 4
backslashes to match a single one.
The regex \w matches a word character. As a C# string, this is written as "\\w".
Basic things to be understood in RegEx:
"*" matches 0 or more patterns "?" matches single character
"^" for ignoring matches. "[]" for searching range patterns.
Example code: You may want to import System.Text.RegularExpressions.
The code below uses regex for validating simple email
149 | P a g e
Regular Expression Basic Syntax
Character Description Example
Any character except [\^$.|?*+()
All characters except the listed special
characters match a single instance of
themselves. { and } are literal characters,
unless they're part of a valid regular
expression token (e.g. the {n} quantifier).
a matches a
\ (backslash) followed
by any of [\^$.|?*+(){}
A backslash escapes special characters to
suppress their special meaning. \+ matches +
\Q...\E Matches the characters between \Q and \E
literally, suppressing the meaning of special
characters.
\Q+-*/\E matches +-*/
\xFF where FF are 2
hexadecimal digits
Matches the character with the specified
ASCII/ANSI value, which depends on the code page used. Can be used in character
classes.
\xA9 matches ©
when using the Latin-1 code page.
\n, \r and \t Match an LF character, CR character and a tab character respectively. Can be used in
character classes.
\r\n matches a
DOS/Windows CRLF line break.
\a, \e, \f and \v Match a bell character (\x07), escape
character (\x1B), form feed (\x0C) and
vertical tab (\x0B) respectively. Can be
used in character classes.
Escape sequences
[ (opening square
bracket)
Starts a character class. A character class
matches a single character out of all the possibilities offered by the character class.
Inside a character class, different rules
apply. The rules in this section are only valid inside character classes. The rules
outside this section are not valid in character classes, except for a few
character escapes that are indicated with "can be used inside character classes".
Any character except ^-
]\ add that character to
All characters except the listed special characters.
[abc] matches a,
b or c
150 | P a g e
the possible matches for the character class.
\ (backslash) followed
by any of ^-]\
A backslash escapes special characters to
suppress their special meaning. [\^\]] matches ^
or ]
- (hyphen) except
immediately after the
opening [
Specifies a range of characters. (Specifies a
hyphen if placed immediately after the
opening [)
[a-zA-Z0-9]
matches any letter
or digit
^ (caret) immediately
after the opening [
Negates the character class, causing it to match a single character not listed in the
character class. (Specifies a caret if placed
anywhere except after the opening [)
[^a-d] matches x
(any character
except a, b, c or d)
\d, \w and \s Shorthand character classes matching digits, word characters (letters, digits, and
underscores), and whitespace (spaces, tabs, and line breaks). Can be used inside
and outside character classes.
[\d\s] matches a
character that is a
digit or whitespace
\D, \W and \S Negated versions of the above. Should be
used only outside character classes. (Can be used inside, but that is confusing.)
\D matches a
character that is not a digit
[\b] Inside a character class, \b is a backspace
character.
[\b\t] matches a
backspace or tab
character
. (dot) Matches any single character except line break characters \r and \n. Most regex
flavors have an option to make the dot
match line break characters too.
. matches x or
(almost) any other character
^ (caret) Matches at the start of the string the regex pattern is applied to. Matches a position
rather than a character. Most regex flavors have an option to make the caret match
after line breaks (i.e. at the start of a line in
a file) as well.
^. matches a in
abc\ndef. Also
matches d in
"multi-line" mode.
$ (dollar) Matches at the end of the string the regex pattern is applied to. Matches a position
rather than a character. Most regex flavors have an option to make the dollar match
before line breaks (i.e. at the end of a line
in a file) as well. Also matches before the very last line break if the string ends with a
line break.
.$ matches f in
abc\ndef. Also
matches c in
"multi-line" mode.
\A Matches at the start of the string the regex pattern is applied to. Matches a position
rather than a character. Never matches
after line breaks.
\A. matches a in abc
\Z Matches at the end of the string the regex pattern is applied to. Matches a position
rather than a character. Never matches before line breaks, except for the very last
line break if the string ends with a line
break.
.\Z matches f in abc\ndef
\z Matches at the end of the string the regex .\z matches f in
151 | P a g e
pattern is applied to. Matches a position rather than a character. Never matches
before line breaks.
abc\ndef
\b Matches at the position between a word
character (anything matched by \w) and a
non-word character (anything matched by
[^\w] or \W) as well as at the start and/or
end of the string if the first and/or last
characters in the string are word characters.
.\b matches c in abc
\B Matches at the position between two word
characters (i.e the position between \w\w)
as well as at the position between two non-
word characters (i.e. \W\W).
\B.\B matches b in abc
| (pipe) Causes the regex engine to match either the part on the left side, or the part on the
right side. Can be strung together into a series of options.
abc|def|xyz
matches abc, def
or xyz
| (pipe) The pipe has the lowest precedence of all operators. Use grouping to alternate only
part of the regular expression.
abc(def|xyz)
matches abcdef or abcxyz
? (question mark) Makes the preceding item optional. Greedy, so the optional item is included in the
match if possible.
abc? matches ab
or abc
?? Makes the preceding item optional. Lazy, so
the optional item is excluded in the match if possible. This construct is often excluded
from documentation because of its limited use.
abc?? matches ab
or abc
* (star) Repeats the previous item zero or more times. Greedy, so as many items as
possible will be matched before trying permutations with less matches of the
preceding item, up to the point where the preceding item is not matched at all.
".*" matches
"def" "ghi" in abc "def" "ghi"
jkl
*? (lazy star) Repeats the previous item zero or more times. Lazy, so the engine first attempts to
skip the previous item, before trying permutations with ever increasing matches
of the preceding item.
".*?" matches
"def" in abc "def" "ghi" jkl
+ (plus) Repeats the previous item once or more.
Greedy, so as many items as possible will be matched before trying permutations with
less matches of the preceding item, up to the point where the preceding item is
matched only once.
".+" matches
"def" "ghi" in abc "def" "ghi"
jkl
+? (lazy plus) Repeats the previous item once or more.
Lazy, so the engine first matches the previous item only once, before trying
permutations with ever increasing matches of the preceding item.
".+?" matches
"def" in abc "def" "ghi" jkl
152 | P a g e
{n} where n is an
integer >= 1
Repeats the previous item exactly n times. a{3} matches aaa
{n,m} where n >= 0
and m >= n
Repeats the previous item between n and
m times. Greedy, so repeating m times is
tried before reducing the repetition to n times.
a{2,4} matches
aaaa, aaa or aa
{n,m}? where n >= 0
and m >= n
Repeats the previous item between n and
m times. Lazy, so repeating n times is tried before increasing the repetition to m times.
a{2,4}? matches
aa, aaa or aaaa
{n,} where n >= 0 Repeats the previous item at least n times. Greedy, so as many items as possible will
be matched before trying permutations with less matches of the preceding item, up to
the point where the preceding item is matched only n times.
a{2,} matches
aaaaa in aaaaa
{n,}? where n >= 0 Repeats the previous item n or more times. Lazy, so the engine first matches the
previous item n times, before trying permutations with ever increasing matches
of the preceding item.
a{2,}? matches aa
in aaaaa
You can learn more about regex Meta-Characters, Character Escapes, etc. in http://www.exforsys.com/tutorials/csharp/regular-expressions-and-csharp-.net.html.
153 | P a g e
7. Exercise
For exercise, you‟ll have to make a program of customer registration. This program will
asks several questions about the customer informations.
The program will validate user‟s input as follow:
1. Email must match with simple email pattern.
154 | P a g e
2. Password min. length is 6 and must contains min. 1 special character.
3. Password Confirmation must same with the password value.
155 | P a g e
4. Last name must be filled.
5. Phone number must match with simple phone pattern.
156 | P a g e
6. The program will close itself after the registration success.
7. The program will close itself to if user click Cancel button.
157 | P a g e
Answer p. Task 1: Create a Window Form Application, resize and rename it:
q. Task 2: Create neccesary labels and components for registration:
r. Task 3: Go to source code view and create neccesary variables:
You may want to import System.Text.RegularExpression because you will use the
Regex class to help email and phone number validation.
Notes: the table below will help you to understand about the email and phone
regex.
Variables Regex Descriptions
emailVal ^((([\w]+\.[\w]+)+)|([\w]+))@(([\w]+\.)+)([A-Za-
^ = start of the regex
() parenthesis = all characters inside
158 | P a g e
z]{1,3})$ parenthesis are single unit
[\w]+ = a digit or a letter and it can repeats because of „+‟
\.[\w]+ can follows with a dot and must followed with a character(s). (i.e. “one.two”)
(([\w]+\.[\w]+)+) will repeat word + dot
+ word. (i.e. “one.two.three.four.five”)
|([\w]+)) = it match word without a dot(s)
to. “|” means alternatif.
((([\w]+\.[\w]+)+)|([\w]+))@ = after
the first char + dot + char it must contains “@”
(([\w]+\.)+) = after “@” you must add
character (word or digit) followed with a dot and repeated.
([A-Za-z]{1,3} = after a dot you only can add a word. And its length must between 1
and 3. (i.e. .com.co.id)
$ = end of the regex
phoneVal ^(\(?[0-9]{3}\)?)?\-?[0-9]{3}\-?[0-9]{4,7}?$
^ = start of the regex
() parenthesis = all characters inside
parenthesis are single unit
(?[0-9]{3}\)?)?\-? = means the first three
digit is optional followed by – (i.e. 021- or (021) – because “\(?“ and “\)?”)
[0-9]{3}\-? = you can add 3 digit and “-“ after the first one. (i.e. (021)-768-)
[0-9]{4,7} means after – you can only add 4
between 7 digit. (i.e. 021-4558938)
159 | P a g e
s. Task 4: Create function that validate the password: The password should contains minimum 1 special character and 6 length.
t. Task 5: Back to design view and create a click event for Register button:
You may want to validate after user click the register button.
u. Task 6: Create a click event for Cancel button: You may want to close the form if user click the cancel button.
160 | P a g e
Chapter 12
Working With Files
161 | P a g e
File and Directory Class
a. File Class
File class is using for the File operations in C#. You can create, delete, copy etc.
operations do with C# File class.
Before using the File class, you may want to import the System.IO namespace first,
because File class is in System.IO.
In order to create a new File using C# File class, you can call Create method in the
File class.
Before you create a File object , you usually check that File exist or not. For that you will use the Exists method in the C# File class.
The following table explains some of common method from File class.
Name Return Type Notes Example
Copy(string source, string dest, bool overwrite)
void Copies an existing file to a
new file. Overwriting a file of the same name is
allowed depends on bool
overwrite value.
File.Copy("C:\\source\file.txt", "C:\\destination\file.txt")
Create(string fileName)
FileStream Creates or Overwrites the
specified file.
File.Create("C:\\temp\file.txt");
Delete(string fileName)
void Deletes the specified file. File.Delete("C:\\temp\file.txt");
Exists(string fileName)
bool Determines wheter the
specified file exists.
File.Exists("C:\\temp\file.txt");
Move(string source, string dest)
void Moves a specified file to a new location, providing
the option to specify a
new file name.
File.Move("C:\\source\file.txt", "C:\\destination\file.txt")
Replace(string source, string dest, string backup)
void Replaces the contents of a specified file with the
contents of another file, deleting the original file,
and creating a backup of
the replaced file.
File.Replace("C:\\source\file.txt", "C:\\destination\file.txt", "C:\\destination\backup.txt")
b. Directory Class Directory Class in C# exposes methods to create, delete, move etc. operations to
directories and subdirectories. Because of the static nature of C# Directory class,
162 | P a g e
you do not have to instantiate the class. You can call the methods in the C#
Directory class directly from the Directory class itself.
Before using the Directory class, you may want to import the System.IO namespace
first, like the File class, Directory class is also in System.IO.
In order to create a new directory using Directory class in C#, you can call
CreateDirectory method directly from Directory class.
Before you creating a directory or folder, you usually check that directory or folder
exist or not. In C# you can use Exists method in the Directory class.
If you want to move a directory and its contents from one location to another , you can use the Move method in the C# Directory class.
When you want to delete a directory you can use the Delete method in the C#
Directory class.
The following table explains some of common method from Directory class.
Name Return Type Notes Example
CreateDirectory(string dirName)
DirectoryInfo Creates all directories
and subdirectories in the specified path.
Directory.CreateDirectory("C:\\new directory")
Delete(string dirName)
void Deletes an empty
directory from a
specified path.
Directory.Delete("C:\\new directory ");
Delete(string dirName, bool delContent)
void Deletes the specified directory and, if
indicated, any subdirectories and files
in the directory.
Directory.Delete("C:\\new directory", true);
Exists(string dirName)
bool Determines whether
the given path refers to an existing directory
on disk.
Directory.Exists("C:\\new directory");
Move(string dirSource, string
void Moves a file or a
directory and its
Directory.Move("C:\\dir", "C:\\dir1\\dir ")
163 | P a g e
dirDest) contents to a new location.
File Streams
The FileStream Class represents a File in the Computer. Use the FileStream class
to read from, write to, open, and close files on a file system, as well as to manipulate other file related operating system handles including pipes, standard input, and standard output.
FileStream allows to move data to and from the stream as arrays of bytes. We operate File
using FileMode in FileStream Class.
Some of FileModes as Follows:
Name Notes
FileMode.Append Open and append to a file if the file does not exists, it create a new file.
FileMode.Create Create a new file, if the file exists it will append to it.
FileMode.CreateNew Create a new file, if the file exists, it throws exception
FileMode.Open Open an existing file
Before using the FileStream class, you may want to import the System.IO namespace
first, like the File & Directory class are also in System.IO.
Binary Reader
C# BinaryReader Object works at lower level of Streams. C# BinaryReader is using
for read primitive types as binary values in a specific encoding stream. Binaryreader Object
works with Stream Objects that provide access to the underlying bytes. For creating a
BinaryReader Object , you have to first create a FileStream Object and then pass
BinaryReader to the constructor method .
The main advantages of Binary information is that stores files as Binary format is the best
practice of space utilization.
Example C# code: (don‟t forget to import the System.IO namespace)
164 | P a g e
Binary Writer
C# BinaryWriter Object works at lower level of Streams. C# BinaryWriter Class is
using for write primitive types as binary values in a specific encoding stream. C#
BinaryWriter Object works with Stream Objects that provide access to the underlying bytes.
For creating a BinaryWriter Object , you have to first create a FileStream Object and then
pass BinaryWriter to the constructor method .
The main advantages of Binary information is that it is not easily human readable and stores files as Binary format is the best practice of space utilization.
Example C# code: (don‟t forget to import the System.IO namespace)
165 | P a g e
8. Exercise
For exercise, you‟ll have to make a program that restore and backup data. This program
will asks several questions about the product informations.
166 | P a g e
Backup button will fire the save open dialog.
The save file dialog allow you to backup the information that user input with determined file type.
Try to clear the text boxes and restore the backup.buc file.
167 | P a g e
The program will reads the backup and write to the textboxes.
Cancel button will close the form after showing a message box.
168 | P a g e
169 | P a g e
Answer v. Task 1: Create a Window Form Application, resize and rename it: w.
x. Task 2: Create neccesary labels and components:
Don‟t forget to add SaveFileDialog for exporting and OpenFileDialog for importing.
y. Task 3: Go to source code view and import System.IO namespace:
You may want to import System.IO namespace because you will use File kind class.
z. Task 4: Add a click event to Restore button:
Restore button will fire the openFileDialog1 dialog.
aa. Task 5: Add a click event to Backup button:
Backup button will fire the saveFileDialog1 dialog.
170 | P a g e
bb. Task 6: Add a FileOK event to saveFileDialog1:
The backup process code will be in this event.
cc. Task 7: Add a FileOK event to openFileDialog1: The restore process code will be in this event.
171 | P a g e
dd. Task 8: Create a click event for Cancel button: You may want to close the form if user click the cancel button.
172 | P a g e
References Chapter 01:
http://www.dotnetspark.com/tutorial/6-36-net-framework.aspx http://www.tipsntracks.com/6/dotnet-framework-overview.html
http://en.wikibooks.org/wiki/C_Sharp_Programming/Foreword http://dump.udderweb.com/Books/software/propriatary/microsoft/Applied%20Microsoft%2
0.NET%20Framework%20Programming%20%282002%29.pdf
References Chapter 02: http://dump.udderweb.com/Books/software/propriatary/microsoft/Applied%20Microsoft%2
0.NET%20Framework%20Programming%20%282002%29.pdf
References Chapter 10:
http://en.wikipedia.org/wiki/Report
References Chapter 11: http://www.exforsys.com/tutorials/csharp/regular-expressions-and-csharp-.net.html.
Book :
C# How to Program by Deitel