3. c# guide advance - to print

50
PROGRAMMING C# Advance Students Guide In partnership with

Upload: chinthaka-fernando

Post on 22-Jan-2017

40 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: 3. C# Guide Advance - To Print

PROGRAMMING C# Advance

Students Guide

In partnership with

Page 2: 3. C# Guide Advance - To Print

Programming C# Advance

Page I

SLANA Technology Learning Centre

Preface

Youth unemployment is high in Sri Lanka’s rural regions, and the disadvantaged youth

population has difficulty in accessing the required knowledge and training which will allow them

to break the existing cycle of poverty to build a better life for themselves. As of 2015, the field of

programming is flourishing on a global scale; nevertheless in rural areas of Sri Lanka, youth have

little to no access to learn programming.

‘Learn the Code that Builds Your World’ project was conceptualized by Sri Lanka Anti

Narcotics Association to address this important issue. This project aims to disseminate

programming knowledge and practical training to youth who previously would not have had the

opportunity to gain access to such teachings; with the ultimate goal of the beneficiaries to

become more employable at the end of their learning experience. One important aspect of this

project’s success is collaborating with relevant organizations, institutes, and schools that identify

apt students and help SLANA disseminate the coding curriculum.

SLANA has been very fortunate to be able to be sponsored by World Bank, Microsoft,

and Sarvodya Fusion to start our Learn the Code that Builds Your World program in Maskeliya

with Tea Leaf Vision being our first collaborative partner.

Page 3: 3. C# Guide Advance - To Print

Programming C# Advance

Page II

SLANA Technology Learning Centre

Introduction

This book is for C# advance programming. As a student you already learnt

what is C# and also the .NET environment. So in this book we are going to cover,

More about Object Oriented Programming (OOP) Concepts.

How to handled Exceptions.

How to design Desktop Application using Visual Studio Environment.

How to handle user interactions with Desktop Application.

Introduction to database with MS SQL.

How to use database with Desktop Applications.

It is very important to have a basic knowledge of C# and Visual Studio

Environment to follow this book. If you haven’t had the basic knowledge

of C# please go through the Programming - C# Basic and come back.

Page 4: 3. C# Guide Advance - To Print

Programming C# Advance

Page III

Sri Lanka Anti Narcotics Association

Table of Contents Chapter 1

Object Oriented Programming ....................................................................................................................... 1 Introduction

Review of Class

Review of Object

Encapsulation

Structs

Parent Class and Child Class

Abstract Classes

Interfaces

Polymorphism and Method Override

Garbage Collection and Destructors

Sealed Classes and Methods

Chapter 2

Introduction to Generic Collections and LINQ ............................................................................................. 9

Chapter 3

Exception Handling ........................................................................................................................................ 13 Exception Handling Overview

Examples of Exceptions

Throw Exceptions

Handle Exceptions with Statements

User Defined Exception Classes

Chapter 4

Threads ........................................................................................................................................................... 17 Introduction to Threads

Create and Execute a thread

Synchronization of Thread

Chapter 5

Events Handling ............................................................................................................................................. 20

Chapter 6

Graphical User Interfaces with Windows Forms ........................................................................................ 22 Create Windows Forms project with Visual Studio

Designing the Layout

A Simple Example for Windows Forms (Calculator)

Chapter 7

Configuration of Database with Microsoft SQL .......................................................................................... 26 Introduction of Databases with Microsoft SQL

Create Database with Microsoft SQL

Create Tables with Microsoft SQL

Insert Data into the tables in Microsoft SQL

About Microsoft SQL Queries

Update tables in Microsoft SQL

Delete Data from the table in Microsoft SQL

Drop Tables(Delete Tables) in Microsoft SQL

Create connection String, DB connect class and DBAccess

DB Connect Class

DBAccess Class

Chapter 8

Handle Database with GUIs .......................................................................................................................... 36 Insert Data into Data Table

Display data into data grids

Update data from table

Delete data from table

References ............................................................................................................................................................ 46

Page 5: 3. C# Guide Advance - To Print

Programming C# Advance

Page 1

Sri Lanka Anti Narcotics Association

Chapter 1 Object Oriented Programming

1.1 Introduction

OOP is a programming style. It stands for Object Oriented Programming. Object-

Oriented Programming (OOP) uses a different set of programming languages than old procedural

programming languages like C, Pascal, etc. Everything in OOP is grouped as self sustainable

"objects". Hence, you gain re-usability by means of four main object-oriented programming

concepts.

Example:

In order to clearly understand the object orientation, let’s take your “hand” as an example.

The “hand” is a class. Your body has two objects of type hand, named left hand and right

hand. Their main functions are controlled/ managed by a set of electrical signals sent

through your shoulders (through an interface). So the shoulder is an interface which your

body uses to interact with your hands. The hand is a well architected class. The hand is

being re-used to create the left hand and the right hand by slightly changing the properties

of it.

1.2 Review of Class

A class is the blueprint/ plan/ template that describe the details of an object. A class is the

blueprint from which the individual objects are created. Class is composed of three things: a

name, attributes, and operations.

Example Code:

class Car

{

//Properties

//Auto Implemented Properties

public String Brand { get; set; }

public String Color { get; set; }

//Constructor

public Car(String brand, String color)

{

this.Brand = brand;

this.Color = color;

}

//Methods

public void ChangeCarColor(String color)

{

this.Color = color;

}

public void ChangeCarBrand(String brand)

{

this.Brand = brand;

}

public void PrintCarDetails()

{

Console.WriteLine(String.Format("Car is {0} in color

and Brand is {1}", Color, Brand));

}

}

Page 6: 3. C# Guide Advance - To Print

Programming C# Advance

Page 2

Sri Lanka Anti Narcotics Association

1.3 Graphical Representation of Class

1.4 Review of Object

An object is an instance of a class. A class must be instantiated into an object before it can

be used in the software. More than one instance of the same class can be in existence at any

one time.

Example of Object Instantiate:

1.5 Encapsulation

Encapsulation is defined 'as the process of enclosing one or more items within a physical or

logical package'. Encapsulation, in object oriented programming methodology, prevents

access to implementation details.

Encapsulation is implemented by using access specifiers. An access specifier defines the

scope and visibility of a class member. C# supports the following access specifiers:

1. Public

2. Private

3. Protected

4. Internal

5. Protected Internal

1. Public Access Specifier

Public access specifier allows a class to expose its member variables and member

functions to other functions and objects. Any public member can be accessed from

outside the class.

2. Private Access Specifier

Private access specifier allows a class to hide its member variables and member

functions from other functions and objects. Only functions of the same class can access

its private members. Even an instance of a class cannot access its private members.

3. Protected Access Specifier

Protected access specifier allows a child class to access the member variables and

member functions of its base class. This way it helps in implementing inheritance.

Car

Brand : String

Color : String

ChangeCarColor(String color) : void

ChangeCarBrand(String brand) : void

PrintCarDetails():void

Class Name

Attributes

Methods

Properties

Car MyCar1 = newCar();

Car MyCar2 = newCar("Benz", "Black");

Figure 1.1

Page 7: 3. C# Guide Advance - To Print

Programming C# Advance

Page 3

Sri Lanka Anti Narcotics Association

4. Internal Access Specifier

Internal access specifier allows a class to expose its member variables and member

functions to other functions and objects in the current assembly. In other words, any

member with internal access specifier can be accessed from any class or method

defined within the namespace in which the member is defined.

5. Protected Internal Access Specifier

The protected internal access specifier allows a class to hide its member variables and

member functions from other class objects and functions, except a child class within

the different namespaces. This is also used while implementing inheritance.

1.6 Structs

Structs may seem similar to classes, but there are important differences that you should be

aware of. First of all, classes are reference types and structs are value types.

Can be created instances of the structs.

Demonstration:

Code:

Sample Output:

class Program

{

Static void Main(string[] args)

{

StructExample structInstance = new StructExample();

structInstance.X = 1;

Console.WriteLine("structInstance.X Value before change :

{0}", structInstance.X);

changeXValue(structInstance);

Console.WriteLine("structInstance.X Value after change :

{0}", structInstance.X);

Console.ReadLine();

}

Public static void changeXValue(StructExample s)

{

//Change X value to 5

s.X = 5;

Console.WriteLine("s.X value inside the method :

{0}",s.X);

}

}

struct StructExample

{

public int X;

}

Figure 1.2

Page 8: 3. C# Guide Advance - To Print

Programming C# Advance

Page 4

Sri Lanka Anti Narcotics Association

1.7 Parent Class and Child Class

1.8 Abstract Classes

Classes can be declared as abstract by putting the keyword abstract before the class

definition.

An abstract class cannot be instantiated. The purpose of an abstract class is to provide a

common definition of a base class that multiple derived classes can share.

About Abstract Methods

Abstract classes may also define abstract methods. This is accomplished by adding the

keyword abstract before the return type of the method. These methods contain only the

signature / prototype of the method.

Example Code:

Static Class

A static class is basically the same as a non-static class, but there is one difference: a static

class cannot be instantiated. In other words, you cannot use the new keyword to create a

variable of the class type. Because there is no instance variable, you access the members of

a static class by using the class name itself.

All the properties (attributes and methods) of the static class must be static.

Vehicle

Car Jeep Lorry

Base / Parent Class

Derived / Child Classes

abstract class Animal

{

String[] Foods { get; set; }

Public abstract void FoodsEat();

}

Figure 1.3

Page 9: 3. C# Guide Advance - To Print

Programming C# Advance

Page 5

Sri Lanka Anti Narcotics Association

Example Code of Static Class:

Way to call the Static Class members:

1.9 Interfaces

An interface contains only the signatures of methods or properties. A class or struct that

implements the interface must implement the members of the interface that are specified in

the interface definition. An interface cannot be instantiated.

An interface can inherit from one or more base interfaces.

Interface members are automatically public, and they can't include any access

modifiers.

Demonstration:

Code:

static class Student

{

public static int Year;

public static void PrintYear()

{

Console.WriteLine(Year);

}

}

Student.Year = 2015;

Student.PrintYear();

interface Vehicle

{

String BrandName { get; set; }

int NoOfWheels { get; set; }

void PrintDetails();

}

//Implement Vehicle interface

class Car : Vehicle

{

//Implement Attributes

public String BrandName{

get{ return brandName;}

set{ brandName = value;}

}

String brandName;

public int NoOfWheels{

get{ return noOfWheels;}

set{ noOfWheels = value;}

}

int noOfWheels;

//Constructor

public Car(){

NoOfWheels = 4;

}

//Implement method

public void PrintDetails(){

Console.WriteLine("Brand of car is {0}", BrandName);

Console.WriteLine("Number of wheels of that car is {0}",

NoOfWheels);

}

}

Car.cs – Implementation of Vehicle Interface

Vehicle.cs

Page 10: 3. C# Guide Advance - To Print

Programming C# Advance

Page 6

Sri Lanka Anti Narcotics Association

1.10 Polymorphism and Method Override

The word polymorphism means having many forms. In Object Oriented Programming,

polymorphism is often expressed as 'one interface, multiple functions'.

Polymorphism is done with overriding the methods. The override key word is used before

the return type to mention the overridden.

Demonstration:

Code:

publicclassShape

{

// A few example members

public int X { get; privateset; }

public int Y { get; privateset; }

public int Height { get; set; }

public int Width { get; set; }

// Virtual method

public virtual void Draw()

{

Console.WriteLine("Performing base class drawing tasks");

}

}

Shape.c

s –

Base

Class

class Circle : Shape

{

public override void Draw()

{

// Code to draw a circle...

Console.WriteLine("Drawing a circle");

//base.Draw();

}

}

class Rectangle : Shape

{

public override void Draw()

{

// Code to draw a rectangle...

Console.WriteLine("Drawing a rectangle");

base.Draw();

}

}

Circle.cs,

Rectangle.cs

– Child

Classes

static void Main(string[] args)

{

Circle circle = new Circle();

circle.Draw();

Rectangle rectangle = new Rectangle();

rectangle.Draw();

Console.ReadLine();

}

Main method

Page 11: 3. C# Guide Advance - To Print

Programming C# Advance

Page 7

Sri Lanka Anti Narcotics Association

Sample Output:

1.11 Garbage Collection and Destructors

1. Garbage Collection

The .NET Framework's garbage collector manages the allocation and release of

memory for your application. Each time you create a new object, the common

language runtime allocates memory for the object from the managed heap. As long as

address space is available in the managed heap, the runtime continues to allocate

space for new objects. However, memory is not infinite. Eventually the garbage

collector must perform a collection in order to free some memory. The garbage

collector's optimizing engine determines the best time to perform a collection, based

upon the allocations being made. When the garbage collector performs a collection, it

checks for objects in the managed heap that are no longer being used by the

application and performs the necessary operations to reclaim their memory.

2. Destructors

In C# it is illegal to call a destructor explicitly it must be called by the garbage

collector. If you handle unmanaged resources that need to be closed and disposed of

as soon as possible,

Demonstration:

Code:

Sample Output:

class Vehicle

{

public Vehicle()

{

Console.WriteLine("Constructor is called");

}

~Vehicle()

{

Console.WriteLine("Destructor is called");

}

}

Figure 1.4

Figure 1.5

Page 12: 3. C# Guide Advance - To Print

Programming C# Advance

Page 8

Sri Lanka Anti Narcotics Association

1.12 Sealed Classes and Methods

1. Sealed Classes

Classes can be declared as sealed by putting the keyword sealed before the class

definition.

A sealed class cannot be used as a base class. For this reason, it cannot also be an

abstract class. Sealed classes prevent derivation. Because they can never be used as a

base class, some run-time optimizations can make calling sealed class members

slightly faster.

2. Sealed Methods

When an instance method declaration includes a sealed modifier, that method is said

to be a sealed method. If an instance method declaration includes the sealed modifier,

it must also include the override modifier. Use of the sealed modifier prevents a

derived class from further overriding the method.

Demonstration:

Code:

Sample Output:

Class Vehicle

{

public int noOfWheels { get; set; }

public virtual void AssignNoOfWheels(int n){}

}

Vehicle.cs

sealed class Car : Vehicle

{

public Car()

{

noOfWheels = 4;

}

public sealed override void AssignNoOfWheels(int n)

{

noOfWheels = n;

}

}

Car.cs – Sealed Class

static void Main(string[] args)

{

Car myCar = newCar();

Console.WriteLine("Number of wheels of car : {0}",

myCar.noOfWheels);

myCar.AssignNoOfWheels(3);

Console.WriteLine("Number of wheels of car after calling method :

{0}", myCar.noOfWheels);

Console.ReadLine();

}

Main method

Figure 1.6

Page 13: 3. C# Guide Advance - To Print

Programming C# Advance

Page 9

Sri Lanka Anti Narcotics Association

Chapter 2 Introduction to Generic Collections and LINQ

2.1. Introduction to Collections

A collection, also called a list, is many items of the same kind grouped into one entity. The

collection can be based on simple numbers, basic symbols, dates, strings, time. The

collection can also be made of objects that each is made of internal values. This means that

a collection can be made of such objects as houses, people, cars, countries, electronic

devices.

The primary rule to observe is that all items included in a list must be described using the

same characteristics. Based on this, if the collection is made of cars, it should contain only

cars, not cars and countries.

There are various types of lists or collections. An array-based list is one whose number of

items is known in advance. For example, an array-based collection of 10 cars contains 10

cars, may be less but not more 10.

Generic Collection Types:

List

Dictionary

List

An array does not dynamically resize. A List does. With it, you do not need to

manage the size on your own. This type is ideal for linear collections not accessed by

keys. Dynamic in size, with many methods, List makes life easier.

Demonstration:

Code:

List<String> list = newList<String>();

//Add elements to integer list

list.Add("Item 1");

list.Add("Item 2");

Console.WriteLine("After adding string elements to the list");

//Walk through each element in the list

foreach (String item in list)

{

Console.WriteLine(item);

}

//Remove elements from integer list

list.Remove("Item 1");

Console.WriteLine("After removing 'Item 1' from the list");

//Walk through each element in the list

foreach (String item in list)

{

Console.WriteLine(item);

}

Console.ReadLine();

Page 14: 3. C# Guide Advance - To Print

Programming C# Advance

Page 10

Sri Lanka Anti Narcotics Association

Sample Output:

Dictionary

Dictionaries provide fast lookups, based on keys to get values. With them, we use

keys and values of any type, including int and string.

Demonstration:

Code:

Sample Output:

2.2. Introduction to LINQ

LINQ stands for Language Integrated Query. A query is an expression that retrieves data

from a data source. Queries are usually expressed in a specialized query language. Different

languages have been developed over time for the various types of data sources, for example

SQL for relational databases and XQuery for XML. Therefore, developers have had to learn

a new query language for each type of data source or data format that they must support.

LINQ simplifies this situation by offering a consistent model for working with data across

Dictionary<int, String> dictionary = newDictionary<int, String>();

//Add elements to dictionary

dictionary.Add(1, "Batman");

dictionary.Add(2, "Spiderman");

dictionary.Add(3, "Superman");

Console.WriteLine("After adding elements to the dictionary");

//Walk through dictionary

foreach (KeyValuePair<int, String> pair in dictionary)

{

Console.WriteLine("{0} {1}",pair.Key,pair.Value);

}

//Remove 2nd element from dictionary list

dictionary.Remove(2);

Console.WriteLine("After removing 2nd element from the dictionary");

foreach (KeyValuePair<int, String> pair in dictionary)

{

Console.WriteLine("{0} {1}", pair.Key, pair.Value);

}

Console.ReadLine();

Figure 2.1

Figure 2.2

Page 15: 3. C# Guide Advance - To Print

Programming C# Advance

Page 11

Sri Lanka Anti Narcotics Association

various kinds of data sources and formats. In a LINQ query, you are always working with

objects. You use the same basic coding patterns to query and transform data in XML

documents, SQL databases, ADO.NET Datasets, .NET collections, and any other format for

which a LINQ provider is available.

Querying an Generic Collection using LINQ Demonstration:

Code:

class Student

{

public staticint Year { get; set; }

public String Name { get; set; }

public String City { get; set; }

public Student(int year,String name,string city)

{

Year = year;

Name = name;

City = city;

}

public void PrintStudentDetail()

{

Console.WriteLine("-------------------------------------------

-------");

Console.WriteLine("Name of the student {0}", Name);

Console.WriteLine("Registered year of the student {0}", Name);

Console.WriteLine("City of residence {0}", City);

Console.WriteLine("-------------------------------------------

-------");

}

}

Student.cs

List<Student> Students = newList<Student>();

Students.Add(newStudent(2015, "Vimal", "Nuwara Eliya"));

Students.Add(newStudent(2015, "Sakumal", "Gampaha"));

Students.Add(newStudent(2015, "Kasun", "Negombo"));

Students.Add(newStudent(2015, "Sumeda", "Kelaniya"));

Students.Add(newStudent(2015, "Kalhara", "Ragama"));

Students.Add(newStudent(2015, "Jayantha", "Gampaha"));

Students.Add(newStudent(2015, "Samantha", "Gampaha"));

//Query to get students who lives in Gampaha

var query = from student in Students

where student.City == "Gampaha"

select student;

List<Student> studentsLiveInGampaha = query.ToList();

Console.WriteLine("Students who lives in Gampaha");

foreach (Student oneStudent in studentsLiveInGampaha)

{

oneStudent.PrintStudentDetail();

}

Console.ReadLine();

Main method

Page 16: 3. C# Guide Advance - To Print

Programming C# Advance

Page 12

Sri Lanka Anti Narcotics Association

Sample Output:

Figure 2.3

Page 17: 3. C# Guide Advance - To Print

Programming C# Advance

Page 13

Sri Lanka Anti Narcotics Association

Chapter 3 Exception Handling 3.1. Exception Handling Overview

The C# language's exception handling features provide a way to deal with any unexpected

or exceptional situations that arise while a program is running. Exception handling uses the

try, catch, and finally keywords to attempt actions that may not succeed, to handle failures,

and to clean up resources afterwards. Exceptions can be generated by the common language

runtime (CLR), by third-party libraries, or by the application code using the throw

keyword.

Exceptions have the following properties:

When your application encounters an exceptional circumstance, such as a division by

zero or low memory warning, an exception is generated.

Use a try block around the statements that might throw exceptions.

Once an exception occurs within the try block, the flow of control immediately jumps to

an associated exception handler, if one is present.

If no exception handler for a given exception is present, the program stops executing

with an error message.

If a catch block defines an exception variable, you can use it to get more information on

the type of exception that occurred.

Actions that may result in an exception are executed with the try keyword.

An exception handler is a block of code that is executed when an exception occurs. In

C#, the catch keyword is used to define an exception handler.

Exceptions can be explicitly generated by a program using the throw keyword.

3.2. Examples of Exceptions:

1. DivideByZeroException

DivideByZeroException indicates that a statement attempted to evaluate a division by

zero. The C# compiler can detect divisions by the constant zero value. The CLR can

throw the exception during program execution.

Example Code:

2. IndexOutOfRangeException

IndexOutOfRangeException happens in C# programs that use array types. This

exception will typically occur when a statement tries to access an element at an index

greater than the maximum allowable index.

//Division by zero exception

// This expression evaluates to 100 / 0, which throws.

// ... You can check the denominator in a separate step.

int result = 100 / int.Parse("0");//Causes the exception

Console.WriteLine(result);

Page 18: 3. C# Guide Advance - To Print

Programming C# Advance

Page 14

Sri Lanka Anti Narcotics Association

Example Code:

3. ArrayTypeMismatchException

The ArrayTypeMismatchException is thrown when an array element location is

assigned to an object whose type is not compatible. It is related to the array

covariance rules.

Example Code:

4. NullReferenceException

The NullReferenceException indicates that you are trying to access member fields, or

function types, on an object reference that points to null.

Example Code:

3.3. Throw Exceptions

The throw statement is used to signal the occurrence of a strange situation (exception)

during the program execution.

Example Code:

//Array index out of range exception

// Allocate an array of one-hundred integers.

// ... Then assign to positions in the array.

// ... Assigning past the last element will throw.

int[] array = newint[100];

array[0] = 1;

array[10] = 2;

array[200] = 3;//Place where the exception occurs

// Array type mismatch exception

// Declares and assigns a string array.

// ... Then implicitly casts to base class object.

// ... Then assigns invalid element.

string[] array1 = { "cat", "dog", "fish" };

object[] array2 = array1;

array2[0] = 5;//Place where the exception occurs

//NullReferenceException

string value = null;

if (value.Length == 0) // <-- Causes exception

{

Console.WriteLine(value); // <-- Never reached

}

static int TakeNumberOf(int index)

{

int[] nums = { 300, 600, 900 };

if (index >= nums.Length){

Thrownew

IndexOutOfRangeException("IndexOutofRangeException

thrown");

}

else{

return nums[index];

}

}

static void Main(string[] args){

int num = TakeNumberOf(3);

Console.ReadLine();

}

Page 19: 3. C# Guide Advance - To Print

Programming C# Advance

Page 15

Sri Lanka Anti Narcotics Association

3.4. Handle Exceptions with Statements

Use try-catch block

The try-catch statement consists of a try block followed by one or more catch clauses, which

specify handlers for different exceptions.

Demonstration:

Code:

Sample Output:

Use try-catch-finally block

A common usage of catch and finally together is to obtain and use resources in a try

block, deal with exceptional circumstances in a catch block, and release the resources

in the finally block.

Demonstration:

Code:

Sample Output:

try

{

int result = 100 / int.Parse("0");

Console.WriteLine(result);

}

catch(DivideByZeroException e)

{

Console.WriteLine(e.Message);

Console.ReadLine();

}

try

{

int[] array = newint[100];

array[0] = 1;

array[10] = 2;

array[200] = 3;

}

catch (IndexOutOfRangeException e)

{

Console.WriteLine(e.Message);

}

finally

{

Console.WriteLine("Execution of finally block");

Console.ReadLine();

}

Figure 3.1

Figure 3.2

Page 20: 3. C# Guide Advance - To Print

Programming C# Advance

Page 16

Sri Lanka Anti Narcotics Association

3.5. User Defined Exception Classes

If you want users to be able to programmatically distinguish between error conditions, you

can create your own user-defined exceptions. The .NET Framework provides a hierarchy of

exception classes ultimately derived from the base class Exception. Each of these classes

defines a specific exception, so in many cases you only have to catch the exception. You

can also create your own exception classes by deriving from the Exception class.

When creating your own exceptions, it is good coding practice to end the class name of the

user-defined exception with the word "Exception." It is also good practice to implement the

three recommended common constructors, as shown in the following example.

Demonstration:

Code:

Sample Output:

//Inheritance with Exception Class

class NumberNotFoundException:Exception

{

public NumberNotFoundException()

{

}

public NumberNotFoundException(string message):

base(message)//Calling the base class constructor

{

}

}

try

{

bool found = false;

int[] a = {5,10,20};

int numberToFind = 15;

for (int i = 0; i < a.Length; i++)

{

if (a[i] == numberToFind)

{

found = true;

}

}

if (found == false)

{

thrownewNumberNotFoundException("Number Not Found");

}

}

catch (NumberNotFoundException e)

{

Console.WriteLine(e.Message);

Console.ReadLine();

}

Main method

NumberNotFoundException.cs – User Defined Exception Class

Figure 3.3

Page 21: 3. C# Guide Advance - To Print

Programming C# Advance

Page 17

Sri Lanka Anti Narcotics Association

Chapter 4 Threads 4.1. Introduction to Threads

Threads are often called lightweight processes. However they are not processes A Thread is

a small set of executable instructions, which can be used to isolate a task from a process.

Multiple threads are efficient way to obtain parallelism of hardware and give interactive

user interaction to your applications.

Threads improve performance. They move computations to a separate logical processor.

They are handled in the .NET Framework with classes from the base class library.

.Net Framework has thread-associated classes in System.Threadingnamespace. The

following steps demonstrate how to create a thread in C#.

Step 1: Create a System.Threading.Thread object.

Creating an object to System.Threading.Thread creates a managed thread in .Net

environment. The Thread class has only one constructor, which takes a ThreadStart

delegate as parameter. The ThreadStart delegate is wrapped around the callback

method, which will be called when we start the thread.

Step 2: Create the call back function

Call back function will be a starting point for our new thread.

Step 3: Starting the Thread

We can start the newly created thread using the Thread’s Start method. This is an

asynchronous method, which requests the operating system to start the current thread.

4.2. Create and Execute a thread

Demonstration:

Code:

static void Main(string[] args){

//Creating the objects of threads with call back functions

//Steps 1 and 2

Thread thread1 = newThread(newThreadStart(FirstMethod));

Thread thread2 = newThread(newThreadStart(SecondMethod));

//Start threads

//Step 3

thread1.Start();

thread2.Start();

Console.ReadLine();

}

//Define call back functions

static void FirstMethod(){

Thread.Sleep(100);

Console.WriteLine("First Method Called");

}

staticvoid SecondMethod(){

Thread.Sleep(1000);

Console.WriteLine("Second Method Called");

}

Page 22: 3. C# Guide Advance - To Print

Programming C# Advance

Page 18

Sri Lanka Anti Narcotics Association

Sample Output:

4.3. Synchronization of Thread

Using a lock or monitor is useful for preventing the simultaneous execution of thread-

sensitive blocks of code, but these constructs do not allow one thread to communicate an

event to another. This requires synchronization events, which are objects that have one of

two states, signaled and un-signaled, that can be used to activate and suspend threads.

Threads can be suspended by being made to wait on a synchronization event that is

signaled, and can be activated by changing the event state to “signaled”. If a thread

attempts to wait on an event that is already signaled, then the thread continues to execute

without delay.

There are two kinds of synchronization events:

AutoResetEvent

ManualResetEvent

AutoResetEvent and ManualResetEvent

They differ only in that AutoResetEvent changes from signaled to “unsignaled”

automatically any time it activates a thread. Conversely, a ManualResetEvent allows

any number of threads to be activated by its signaled state, and will only revert to an

“unsignaled” state when its Reset method is called.

Threads can be made to wait on events by calling one of the wait methods, such as

“WaitOne”, “WaitAny”, or “WaitAll”. “WaitHandle.WaitOne()” causes the thread to

wait until a single event becomes signaled, “WaitHandle.WaitAny()” blocks a thread until

one or more indicated events become signaled, and “WaitHandle.WaitAll()” blocks the

thread until all of the indicated events become signaled. An event becomes signaled when

its Set method is called.

In the following example, a thread is created and started by the Main function. The new

thread waits on an event using the “WaitOne” method. The thread is suspended until the

event becomes signaled by the primary thread that is executing the Main function. Once the

event becomes signaled, the auxiliary thread returns. In this case, because the event is only

used for one thread activation, either the “AutoResetEvent” or “ManualResetEvent”

classes could be used.

Figure 4.1

Page 23: 3. C# Guide Advance - To Print

Programming C# Advance

Page 19

Sri Lanka Anti Narcotics Association

Example Code:

static AutoResetEvent autoEvent;

static void DoWork()

{

Console.WriteLine("\tworker thread started, now waiting on

event...");

autoEvent.WaitOne();

Console.WriteLine("\tworker thread reactivated, now

exiting...");

}

static void Main(string[] args)

{

autoEvent = new AutoResetEvent(false);

Console.WriteLine("main thread starting worker thread...");

Thread t = new Thread(DoWork);

t.Start();

Console.WriteLine("main thread sleeping for 2 second...");

Thread.Sleep(2000);

Console.WriteLine("main thread signaling worker thread...");

autoEvent.Set();

Console.ReadLine();

}

Page 24: 3. C# Guide Advance - To Print

Programming C# Advance

Page 20

Sri Lanka Anti Narcotics Association

Chapter 5 Events Handling

An event is a mechanism via which a class can notify its clients when something happens.

For example when you click a button, a button-click-event notification is sent to the window

hosting the button. Events are declared using delegates.

Demonstration:

Code:

class DivisionByFiveEventListener

{

public void ShowOnScreen(object o, DivisionByFiveEventArg e)

{

Console.WriteLine(

"divisible by five event raised!!! The number is {0}",

e.TheNumber);

}

}

class DivisionByFiveEventArg:EventArgs

{

public readonly int TheNumber;

public DivisionByFiveEventArg(int num)

{

TheNumber = num;

}

}

public delegate void DivisionByFiveHandler(object o,

DivisionByFiveEventArg e);

public static event DivisionByFiveHandler EventFive;

static void Main(string[] args){

DivisionByFiveEventListener dbsl = newDivisionByFiveEventListener();

EventFive += newDivisionByFiveHandler(dbsl.ShowOnScreen);

GenNumbers();

Console.ReadLine();

}

publicstaticvoid OnEventFive(DivisionByFiveEventArg e){

if (EventFive != null)

EventFive(newobject(), e);

}

publicstaticvoid GenNumbers(){

for (int i = 0; i <= 50; i++)

{

if (i % 5 == 0)

{

DivisionByFiveEventArg e1 = newDivisionByFiveEventArg(i);

OnEventFive(e1);

}

}

}

DivisionByFiveEventListener.cs

DivisionByFiveEventArg.cs

Main program class

Page 25: 3. C# Guide Advance - To Print

Programming C# Advance

Page 21

Sri Lanka Anti Narcotics Association

Sample Output:

Figure 5.1

Page 26: 3. C# Guide Advance - To Print

Programming C# Advance

Page 22

Sri Lanka Anti Narcotics Association

Chapter 6 Graphical User Interfaces with Windows Forms

6.1. Create Windows Forms project with Visual Studio

1. In Visual Studio 2008 select File>New> Project from the menu. This will open the below

window.

2. Select Windows Forms Application and type a name for the project and click OK.

This will create the Windows Form Project.

Type Name here

Project type

Figure 6.1

Figure 6.2

Page 27: 3. C# Guide Advance - To Print

Programming C# Advance

Page 23

Sri Lanka Anti Narcotics Association

Window to create Windows Form Application

6.2. Designing the Layout

Use Toolbox to design the Form. Drag and drop the item you want to display in the form

from the toolbox to design view.

To change the item’s display properties go to property window and change the value which

you want to change. To enable the property window right click on the item and select

Properties from the list.

Use property window to change:

Properties Tab:

Name of the item (which used to identify each item in the form uniquely)

Background Color

Foreground Color

Height and width etc.

Events Tab – Can be used to handle user inputs (Discussed later):

Click event

Key pressed event

Toolbox

Designer

Figure 6.3

Page 28: 3. C# Guide Advance - To Print

Programming C# Advance

Page 24

Sri Lanka Anti Narcotics Association

6.3. A Simple Example for Windows Forms (Calculator)

1. First create a windows form application with visual studio and name it as

SimpleExampleCal.

2. In the design view, design it as follows.

3. Add code as follows to the Code behind of the Form.

Add button click events to numbers and decimal point as following example.

Example:

private void ZeroClick(object sender, EventArgs e)

{

DisplayTextBox.Text += "0";

}

Events Tab

Property

Window

Property Tab

Properties

Figure 6.4

Figure 6.5

Page 29: 3. C# Guide Advance - To Print

Programming C# Advance

Page 25

Sri Lanka Anti Narcotics Association

Add button click events to operators as follows

Example:

Add clear button click event as follows.

Code:

Add a method to calculate the value as follows.

Code:

Add answer button click event as follows.

Code:

private void PlusClick(object sender, EventArgs e)

{

if (operatorChar.Equals(' '))

{

answer = Double.Parse(DisplayTextBox.Text);

}

else

{

CalculateValueWithOperator();

}

operatorChar = '+';

DisplayTextBox.Text = "";

}

private void ClearButton(object sender, EventArgs e)

{

DisplayTextBox.Text = "";

answer = 0;

}

private void CalculateAnswer(object sender, EventArgs e)

{

if(!DisplayTextBox.Text.Equals(""))

{

CalculateValueWithOperator();

DisplayTextBox.Text = answer.ToString();

}

answer = 0;

}

private void CalculateValueWithOperator()

{

switch (operatorChar)

{

case'+':

answer += Double.Parse(DisplayTextBox.Text);

break;

case'-':

answer -= Double.Parse(DisplayTextBox.Text);

break;

case'*':

answer *= Double.Parse(DisplayTextBox.Text);

break;

case'/':

answer /= Double.Parse(DisplayTextBox.Text);

break;

}

}

Page 30: 3. C# Guide Advance - To Print

Programming C# Advance

Page 26

Sri Lanka Anti Narcotics Association

Chapter 7 Configuration of Database with Microsoft SQL

7.1 Introduction of Databases with Microsoft SQL

Database:

A database is structured collection of data.Computer-based databases are usually

organised into one or more tables. A table stores data in a format similar to a published

table and consists of a series of rows and columns. To carry the analogy further, just as

a published table will have a title at the top of each column, so each column in a

database table will have a name, often called a field name. The term field is often used

instead of column. Each row in a table will represent one example of the type of object

about which data has been collected. One row or one record is called as tuple.

Example for table: Population of different towns

Primary Key:

The primary key of a relational table uniquely identifies each record in the table. It can

either be a normal attribute that is guaranteed to be unique. Primary keys may consist

of a single attribute or multiple attributes in combination.

Example:

You can take Town and County together as Primary Key since Town and

County unique.

Foreign Key:

A foreign key is a column or group of columns in a relational database table that

provides a link between data in two tables. It acts as a cross-reference between tables

because it references the primary key of another table, thereby establishing a link

between them.

Example: Sizes of different towns

Town County Population

Welwyn Garden City Hertfordshire 40,570

St. Albans Hertfordshire 123,800

Hertford Hertfordshire 2,023

Durham Durham 29,490

Town County Size /square miles

Welwyn Garden City Hertfordshire 650

St. Albans Hertfordshire 433

Hertford Hertfordshire 232

Durham Durham 4050

Fields

Tuples

Table 7.1

Table 7.2

Page 31: 3. C# Guide Advance - To Print

Programming C# Advance

Page 27

Sri Lanka Anti Narcotics Association

Town and County is the foreign key field. It references to the Town and

County (Primary key of Population Table) of the Population Table.

We are going to use Microsoft SQL to create and manage the databases. SQL stands for

Structured Query Language. SQL lets you access and manipulate databases. SQL is an

ANSI (American National Standards Institute) standard.

SQL do the following tasks

SQL can execute queries against a database.

SQL can retrieve data from a database.

SQL can insert records in a database.

SQL can update records in a database.

SQL can delete records from a database.

SQL can create new databases.

SQL can create new tables in a database.

SQL can create stored procedures in a database.

SQL can create views in a database.

SQL can set permissions on tables, procedures, and views.

7.2 Create Database with Microsoft SQL 1. Open Microsoft SQL Server Management Studio Express.

Click Connect button in the above window to connect to local server.

2. Then right click on the databases and click New Database from the list.

Figure 7.1

Figure 7.2

Page 32: 3. C# Guide Advance - To Print

Programming C# Advance

Page 28

Sri Lanka Anti Narcotics Association

3. Then type a name for the database and click OK button to create a new database.

4. Then Click on New Query to open a text editor to type queries.

Figure 7.3

Figure 7.4

Page 33: 3. C# Guide Advance - To Print

Programming C# Advance

Page 29

Sri Lanka Anti Narcotics Association

7.3 Create Tables with Microsoft SQL

Syntax to create a table

Example:

After typing the query select the database from the database list and click Execute button

to create the table.

7.4 Insert Data into the tables in Microsoft SQL

Syntax to insert data into the table

Example:

CREATE TABLE table_name

(

column_name1 data_type(size),

column_name2 data_type(size),

column_name3 data_type(size),

...

);

CreateTable MyFirstTable

(

ID intPrimaryKey,

Namevarchar(50)

)

Database list Execute Button

INSERT INTO table_name

VALUES (value1,value2,value3,...);

--First insert statement

Insertinto MyFirstTable values(1,'Saman');

--Second insert statement

Insertinto MyFirstTable values(2,'Raj');

--Third insert statement

Insertinto MyFirstTable values(3,'Pasan');

Comment

Figure 7.5

Page 34: 3. C# Guide Advance - To Print

Programming C# Advance

Page 30

Sri Lanka Anti Narcotics Association

7.5 About Microsoft SQL Queries

SQL Select Statement - The SELECT statement is used to select data from a database.

Syntax to select statement:

1. To retrieve specified columns from a given table

2. To retrieve all columns from a given table.

Examples:

3. Remove duplicate rows and retrieve only the unique data

Use DISTINCT keyword with select statement.

Demonstration without Distinct keyword:

Code:

Sample Output:

Demonstration with Distinct keyword:

Code:

Sample Output:

SELECT column_name,column_name

FROM table_name;

SELECT * FROM table_name;

--Retrieve only the names from the table

SelectName

From MyFirstTable

--Retrieve all the information from the table

Select*

From MyFirstTable

SelectName

From MyFirstTable

SelectDISTINCTName

From MyFirstTable

Figure 7.6

Figure 7.7

Page 35: 3. C# Guide Advance - To Print

Programming C# Advance

Page 31

Sri Lanka Anti Narcotics Association

SQL Where Statement – The WHERE clause is used to extract only those records that

fulfill a specified criterion

Syntax to where statement:

Demonstration:

Code:

Sample Output:

SQL Orderby Statement - The ORDER BY keyword is used to sort the result-set by

one or more columns.

Syntax to ORDER BY statement:

Demonstration:

Code:

Sample Output:

SELECT column_name,column_name

FROM table_name

WHERE <Condition>

--Use of where clause

Select ID,Name

From MyFirstTable

Where ID>1

SELECT column_name,column_name

FROM table_name

ORDER BY <column_name> ASC |DESC

--Use of orderby clause

SelectDISTINCTName

From MyFirstTable

OrderbyNameASC

Figure 7.8

Figure 7.9

Page 36: 3. C# Guide Advance - To Print

Programming C# Advance

Page 32

Sri Lanka Anti Narcotics Association

7.6 Update tables in Microsoft SQL

Syntax to update tables

Demonstration before updating the table:

Code: Sample Output:

Demonstration with update statement:

Code:

Sample Output after updating:

7.7 Delete Data from the table in Microsoft SQL

Syntax to delete data from table

Demonstration before deleting the data from the table:

Code: Sample Output:

UPDATE table_name

SET column1=newValue1,column2=newValue2,...

WHERE some_column=some_value;

Select*

From MyFirstTable

--Update statement

Update MyFirstTable

SetName='Samantha Perera'

Where ID = 1

--Retrieve all the

information from the table

Select*

From MyFirstTable

DELETE FROM table_name

WHERE some_column=some_value;

Select*

From MyFirstTable

Figure 7.10

Figure 7.11

Figure 7.12

Page 37: 3. C# Guide Advance - To Print

Programming C# Advance

Page 33

Sri Lanka Anti Narcotics Association

Demonstration with update statement:

Code:

Sample Output after deleting:

7.8 Drop Tables(Delete Tables) in Microsoft SQL

Syntax to drop table

Code to Drop Table:

7.9 Create connection String, DB connect class and DBAccess class

Connection String

Add Application Configuration File from Add New Item Window to Project.

--Delete Data from the table

DELETEFROM MyFirstTable

WHERE ID = 2

--Retrieve all the

information from the table

Select*

From MyFirstTable

Drop Table table_name;

Drop Table MyFirstTable

Figure 7.13

Figure 7.14

Page 38: 3. C# Guide Advance - To Print

Programming C# Advance

Page 34

Sri Lanka Anti Narcotics Association

Add following code to App.config file which was added in the above step. It describes

the database connection of the windows form application.

Connection String:

7.10 DB Connect Class

Add class with the name DBConnect to the project.

This class helps to access database objects through our program.

The purpose of having a separate class for this is to develop the project in a structured

manner, which will help avoid having to develop the same code in multiple places of the

program.

Code of DBConnectClass:

Then add the following code to namespace list which is in the above part of the DBConnect

class.

Code:

Then right click on the project name and click “Add Reference”.

<connectionStrings>

<addname="ConString"

connectionString="Data Source=ServerName;

Initial Catalog=DatabaseName;Integrated Security=True"

providerName="System.Data.SqlClient" />

</connectionStrings>

class DBConnect

{

public static SqlConnection newConnection;

public static string connectionString =

ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;

public static SqlConnection GetConnection()

{

newConnection = newSqlConnection(connectionString);

return newConnection;

}

}

using System.Data.SqlClient;

Connection name as in the connection string

Figure 7.15

Page 39: 3. C# Guide Advance - To Print

Programming C# Advance

Page 35

Sri Lanka Anti Narcotics Association

This will open the following window. Select the “System.Configuration”reference from the

list and click OK. It will add a reference “System.Configuration”.

Then add the following namespace.

Code:

7.11 DBAccess Class

Add DBAccess class to the project.

This class is created to implement methods, which will be used to access database objects

and return them to the form. (Insert/Update and Delete methods)

Code of DBAccess Class:

Then add the following namespace to DBAccess class.

Code:

using System.Configuration;

class DBAccess

{

public DBAccess()

{

connection = DBConnect.GetConnection();

}

SqlConnection connection;

}

using System.Data.SqlClient;

Figure 7.16

Page 40: 3. C# Guide Advance - To Print

Programming C# Advance

Page 36

Sri Lanka Anti Narcotics Association

Chapter 8 Handle Database with GUIs

8.1 Insert Data into Data Table Example:

Design the Form Windows as follows.

Add names for the textboxes from the properties window as follows.

Book Name - bookName

Author - author

Edition - edition

Price - price

Published Year - publishedYear

Create database called “BookDB” from Microsoft SQL 2005 Management Studio.

Create table called “BookDetails”.

Code for create table:

Add a class to the project and name it as “Book”.

Code:

public class Book{

//Attributes

public int BookID { get; set; }

public String BookName { get; set; }

public String Author { get; set; }

public int Edition { get; set; }

public double Price { get; set; }

public int YearPublished { get; set; }

//Default Constructor

public Book(){ }

}

CreateTable BookDetails(

BookID intidentity(1,1)PrimaryKey,

BookName varchar(200),

AuthorName varchar(200),

Edition int,

Price float,

PublishedYear int

)

Figure 8.1

Page 41: 3. C# Guide Advance - To Print

Programming C# Advance

Page 37

Sri Lanka Anti Narcotics Association

Add insert method to DBAccess class to add new record to “BookDetails” Table.

Code:

Create a DBAccess object in “Book” class. This will be used to access the methods of

the DBAccess class.

Code:

Add a method to “Book” class to call the insert method with the values.

Code:

Create a book object in code behind of the form.

Code:

Add validation method validate textboxes.

//Insert data into book table

public bool InsertDataToBookTable(String bookName, String authorName,

int edition, double price, int publishedYear)

{

//Check if connection is closed, if it is closed open it

if (connection.State == ConnectionState.Closed)

{

connection.Open();

}

using (SqlCommand newCmd = connection.CreateCommand())

{

try

{

newCmd.Connection = connection;

newCmd.CommandType = CommandType.Text;

//Query to insert new book

String query = String.Format("Insert into BookDetails

values ('{0}','{1}',{2},{3},{4})",

bookName,authorName,edition,price,publishedYear);

newCmd.CommandText = query;

newCmd.ExecuteNonQuery();

}

finally

{

connection.Close();

}

}

return true;

}

public bool InsertNewBook()

{

//Call the method of DBAccess class to insert a new book

bool isInserted = access.InsertDataToBookTable(BookName,

Author, Edition, Price, YearPublished);

return isInserted;

}

DBAccess access = newDBAccess();

DBAccess access = newDBAccess();

Page 42: 3. C# Guide Advance - To Print

Programming C# Advance

Page 38

Sri Lanka Anti Narcotics Association

Add button click events to “Add to DB” and “Clear” buttons from the Events tab of

the properties window.

Code Behind of Add New Book Form:

public partial class AddABook : Form

{

public AddABook()

{

InitializeComponent();

}

//Create a Book object

Book newBook = newBook();

//AddToDB button click

private void addToDB_Click(object sender, EventArgs e)

{

//Validate textboxes

String validationString = Validation();

if (validationString.Equals("Success"))

{

//Assign textbox values to variables of book object

newBook.BookName = bookName.Text;

newBook.Author = author.Text;

newBook.Edition = int.Parse(edition.Text);

newBook.Price = double.Parse(price.Text);

newBook.YearPublished = int.Parse(publishedYear.Text);

bool isInserted = newBook.InsertNewBook();

if (isInserted)

{

MessageBox.Show("Book details Insertion

successful!");

clearTextBoxes();

}

else

{

MessageBox.Show("Insertion unsuccessful! Please

check the data you entered.");

}

}

else

{

MessageBox.Show(validationString);

}

}

//Clear button click

privatevoid clear_Click(object sender, EventArgs e)

{

clearTextBoxes();

}

//Method to clear textboxes of the form

private void clearTextBoxes()

{

bookName.Text = "";

author.Text = "";

edition.Text = "";

price.Text = "";

publishedYear.Text = "";

}

}

Page 43: 3. C# Guide Advance - To Print

Programming C# Advance

Page 39

Sri Lanka Anti Narcotics Association

Code behind Continued(Validation Method):

8.2 Display data into data grids

Design the form as follows.

Change the following properties of the datagridview.

Name : booksDataGrid

AllowUserToAddRows : true

//Method to validate textboxes

private String Validation()

{

bool isEmpty = true;

isEmpty = isEmpty && bookName.Text.Equals("");

isEmpty = isEmpty && author.Text.Equals("");

isEmpty = isEmpty && edition.Text.Equals("");

isEmpty = isEmpty && price.Text.Equals("");

isEmpty = isEmpty && publishedYear.Text.Equals("");

if (isEmpty)

{

return "Please fill all the fields";

}

else

{

try

{

newBook.Edition = int.Parse(edition.Text);

newBook.Price = double.Parse(price.Text);

newBook.YearPublished =

int.Parse(publishedYear.Text);

}

catch (FormatException)

{

return "Please enter numbers for Edition, Price

and Year Published";

}

return "Success";

}

}

Figure 8.2

Page 44: 3. C# Guide Advance - To Print

Programming C# Advance

Page 40

Sri Lanka Anti Narcotics Association

Add a method in “DBAccess” class to retrieve data table from database.

Code:

Code behind of ViewBookDetails Form

public DataTable RetrieveAllBooks()

{

if (connection.State == ConnectionState.Closed)

{ connection.Open(); }

using (SqlCommand newCmd = connection.CreateCommand())

{

try

{

newCmd.Connection = connection;

newCmd.CommandType = CommandType.Text;

newCmd.CommandText = "Select * From BookDetails";

SqlDataAdapter da = newSqlDataAdapter(newCmd);

DataTable dt = newDataTable();

da.Fill(dt); return dt;

}

finally

{ connection.Close(); }

}

}

public partial class ViewBooks : Form

{

public ViewBooks()

{

InitializeComponent();

getAllBooks();

setTheColumnNames();

formattingThePrice();

setTheAlignmentsOfTheContent();

setColumnAutoSize();

addEditAndDeleteButtonColumns();

}

BindingList<Book> allBooks;

DBAccess access = newDBAccess();

private void getAllBooks()

{

allBooks = newBindingList<Book>();

//Retrieve books

DataTable books = access.RetrieveAllBooks();

foreach (DataRow oneBook in books.Rows)

{

Book currentBook = newBook();

currentBook.BookID =

int.Parse(oneBook["BookID"].ToString());

currentBook.BookName = oneBook["BookName"].ToString();

currentBook.Author = oneBook["AuthorName"].ToString();

currentBook.Edition =

int.Parse(oneBook["Edition"].ToString());

currentBook.Price =

double.Parse(oneBook["Price"].ToString());

currentBook.YearPublished =

int.Parse(oneBook["PublishedYear"].ToString());

allBooks.Add(currentBook);

}

//Set the datagrid data

booksDataGrid.DataSource = allBooks;

}

Page 45: 3. C# Guide Advance - To Print

Programming C# Advance

Page 41

Sri Lanka Anti Narcotics Association

Code Behind Continued:

8.3 Update data from table Add following Update method inside the “DBAccess” class.

private void setTheColumnNames()

{

//Set the column names

booksDataGrid.Columns[0].HeaderText = "Book ID";

booksDataGrid.Columns[1].HeaderText = "Book Name";

booksDataGrid.Columns[2].HeaderText = "Author";

booksDataGrid.Columns[3].HeaderText = "Edition";

booksDataGrid.Columns[4].HeaderText = "Price";

booksDataGrid.Columns[5].HeaderText = "Year Published";

}

private void formattingThePrice()

{

//Formatting the price as Rs 0.00

booksDataGrid.Columns[4].DefaultCellStyle.Format = "Rs

0.00";

}

private void setTheAlignmentsOfTheContent()

{

//Set the alignment of the content

booksDataGrid.Columns[3].DefaultCellStyle.Alignment =

DataGridViewContentAlignment.MiddleCenter;

booksDataGrid.Columns[4].DefaultCellStyle.Alignment =

DataGridViewContentAlignment.MiddleRight;

booksDataGrid.Columns[5].DefaultCellStyle.Alignment =

DataGridViewContentAlignment.MiddleCenter;

}

privatevoid setColumnAutoSize()

{

booksDataGrid.AutoSizeColumnsMode =

DataGridViewAutoSizeColumnsMode.AllCells;

}

//Update book details

public void UpdateBookDetails(int bookID,String bookNameNew, String

authorNameNew, int editionNew, double priceNew, int publishedYearNew)

{

if (connection.State == ConnectionState.Closed)

{ connection.Open(); }

using (SqlCommand newCmd = connection.CreateCommand())

{

try{

newCmd.Connection = connection;

newCmd.CommandType = CommandType.Text;

String query = String.Format("update BookDetails set

BookName='{0}',AuthorName='{1}',Edition={2},Price={3},PublishedYear

={4} where

BookID={5}",bookNameNew,authorNameNew,editionNew,priceNew,publishedYearN

ew,bookID);

newCmd.CommandText = query;

newCmd.ExecuteNonQuery();

}finally

{ connection.Close(); }

}

}

Page 46: 3. C# Guide Advance - To Print

Programming C# Advance

Page 42

Sri Lanka Anti Narcotics Association

Add a method to “Book” class to call the update method with the values.

Code:

Add a method to define edit and delete button columns to Code behind of ViewBookDetails

Form.

Code:

Define edit detail page to edit book details.

public void UpdateBookDetail()

{

access.UpdateBookDetails(BookID,BookName,Author,Edition,Price,

YearPublished);

}

private void addEditAndDeleteButtonColumns()

{

//Add edit button column

DataGridViewButtonColumn editColumn = new

DataGridViewButtonColumn();

editColumn.HeaderText = "Edit Details";

editColumn.Text = "Edit";

//To Display text inside the button

editColumn.UseColumnTextForButtonValue = true;

//Add button click event to Edit button

booksDataGrid.CellContentClick += new

DataGridViewCellEventHandler(editButtonClick);

booksDataGrid.Columns.Insert(6, editColumn);

//Add delete button column

DataGridViewButtonColumn deleteColumn = new

DataGridViewButtonColumn();

deleteColumn.HeaderText = "Delete Book";

deleteColumn.Text = "Delete";

//To Display text inside the button

deleteColumn.UseColumnTextForButtonValue = true;

booksDataGrid.Columns.Insert(7, deleteColumn);

//Add button click event to Delete button

booksDataGrid.CellContentClick += new

DataGridViewCellEventHandler(deleteButtonClick);

}

Figure 8.3

Page 47: 3. C# Guide Advance - To Print

Programming C# Advance

Page 43

Sri Lanka Anti Narcotics Association

Code behind of Edit Detail Form:

public partial class EditBookDetails : Form

{

public EditBookDetails(Book selectedBookToEdit)

{

InitializeComponent();

bookToEdit = selectedBookToEdit;

bookName.Text = bookToEdit.BookName;

author.Text = bookToEdit.Author;

edition.Text = bookToEdit.Edition.ToString();

price.Text = bookToEdit.Price.ToString();

publishedYear.Text = bookToEdit.YearPublished.ToString();

}

Book bookToEdit;

private void editDetailsButton_Click(object sender, EventArgs e)

{

//Validate textboxes

String validationString = Validation();

if (validationString.Equals("Success")){

DialogResult comfirmationResult = MessageBox.Show("Are

you sure?", "Edit this Book details",

MessageBoxButtons.YesNo);

if (comfirmationResult == DialogResult.Yes){

//Set new values

bookToEdit.BookName = bookName.Text;

bookToEdit.Author = author.Text;

//Rest added inside validation method

bookToEdit.UpdateBookDetail();

MessageBox.Show("Edit details successful");

}

}

else{

MessageBox.Show(validationString); }

}

//Method to validate textboxes

private String Validation()

{

bool isEmpty = true;

isEmpty = isEmpty && bookName.Text.Equals("");

isEmpty = isEmpty && author.Text.Equals("");

isEmpty = isEmpty && edition.Text.Equals("");

isEmpty = isEmpty && price.Text.Equals("");

isEmpty = isEmpty && publishedYear.Text.Equals("");

if (isEmpty) {

return"Please fill all the fields"; }

else{

try {

bookToEdit.Edition = int.Parse(edition.Text);

bookToEdit.Price = double.Parse(price.Text);

bookToEdit.YearPublished =

int.Parse(publishedYear.Text);

} catch (FormatException){

return "Please enter numbers for Edition, Price

and Year Published";

}

return"Success";

}

}

}

Page 48: 3. C# Guide Advance - To Print

Programming C# Advance

Page 44

Sri Lanka Anti Narcotics Association

Add method to define Edit button click event

8.4 Delete data from table Add delete method to DBAccess class to delete the book details you entered in the

insertion step.

Code:

Add a method to “Book” class to call the delete method with the BookID which you

want to delete.

Code:

void editButtonClick(object sender, DataGridViewCellEventArgs e)

{

//e.RowIndex != -1 to remove the header of the column

if (e.ColumnIndex == 0 && e.RowIndex !=-1)

{

//Get selected index

int selectedIndex = booksDataGrid.CurrentRow.Index;

EditBookDetails editBookDetailWindow = new

EditBookDetails(allBooks[selectedIndex]);

editBookDetailWindow.ShowDialog();

}

}

//Delete book details

public void DeleteBookDetails(int bookID)

{

if (connection.State == ConnectionState.Closed)

{

connection.Open();

}

using (SqlCommand newCmd = connection.CreateCommand())

{

try

{

newCmd.Connection = connection;

newCmd.CommandType = CommandType.Text;

String query = "Delete From BookDetails where

BookID = "+ bookID;

newCmd.CommandText = query;

newCmd.ExecuteNonQuery();

}

finally

{

connection.Close();

}

}

}

public void DeleteBookDetail()

{

access.DeleteBookDetails(BookID);

}

Page 49: 3. C# Guide Advance - To Print

Programming C# Advance

Page 45

Sri Lanka Anti Narcotics Association

Add method to define Delete button click event

void deleteButtonClick(object sender, DataGridViewCellEventArgs e)

{

if (e.ColumnIndex == 1 && e.RowIndex != -1)

{

DialogResult comfirmationResult = MessageBox.Show("Are you

sure?", "Delete this Book details",

MessageBoxButtons.YesNo);

if (comfirmationResult == DialogResult.Yes)

{

//Get selected index

int selectedIndex = booksDataGrid.CurrentRow.Index;

Book selectedBook = allBooks[selectedIndex];

selectedBook.DeleteBookDetail();

allBooks.Remove(selectedBook);

booksDataGrid.Refresh();

}

}

}

Page 50: 3. C# Guide Advance - To Print

Programming C# Advance

Page 46

Sri Lanka Anti Narcotics Association

References Microsoft Cooperation. [ONLINE] Available at: http://msdn.microsoft.com.

[Last Accessed 2015 January 18].

Sam Allen (2007). [ONLINE] Available at: http://www.dotnetperls.com/.

[Last Accessed 2015 January 02].

Code Project (1999).

[ONLINE] Available at: http://www.codeproject.com/kb/cs/.

[Last Accessed 2015 January 10].

Stack Exchange. [ONLINE] Available at: http://stackoverflow.com/.

[Last Accessed 2015 January 23].

Tutorials Point. [ONLINE] Available at: http://www.tutorialspoint.com/.

[Last Accessed 2015 January 15].