C-Prog - TextBook by Khan Sir
C-Prog - TextBook by Khan Sir
C-Prog - TextBook by Khan Sir
.NET is a platform to design and develop different application; it comes bundled in the form of
visual studio. Visual Studio 2010 is more than just the next version of Visual Studio to use
with the next version of the .NET Framework. Visual Studio 2010 continues Microsoft’s
attempt to position Visual Studio as a tool we can use for the upstream and downstream
development activities that sandwich actual code writing. For example, we can use Visual
Studio to visually model the entities we want to create in code. Unlike other modeling tools
that have only a one-way relationship between the model and the code generation, our code
stays synchronized with the model.
Visual Studio 2010 is a complete rewrite of the user interface, but the familiar commands and
tools that we have come to know and love are still there. We will notice a completely revised,
intuitive, and modern
user interface that showcases the tremendous leaps that Visual Studio has made since the
release of Visual Studio .NET back in 2002.
Visual Studio 2010 provides a dizzying array of editors, controls, designers, and supporting
tools for developing software.
The programming languages of .NET: The four languages that Microsoft Visual studio
2010 offers (in addition to dozens more that are available from third parties):
❖ VB.NET (Visual Basic)
❖ C#
❖ C++
❖ F# (New programming language)
In this book we are using C# language for developing the following three types of
applications:
❖ Console Applications
❖ Windows applications
❖ ASP.NET Web Applications
.NET is a well known platform for developing console, windows and the web application. It is
one of the best products of Microsoft after windows. .NET runs on the windows and the web
applications run on the IIS server of windows which comes inbuilt with windows operating
system. The best thing about .NET is that we can use different languages for any of the
application according to our convenience and can design and run the program in the same
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
2
window without any other editor; because it has a great IDE for designing and developing
many different application using different languages.
.NET has the best IDE (Integrated Development Environment) for developing any types of
application; IDE is the platform where we can design, code and run the application without
the support of other application. .NET IDE includes following components to develop and run
the application:
• Solution Explorer
• Properties Window
• Tool Box
• Server Explorer
• Form/class/webpage(designing and coding area)
• Menu Bar
• Tool Bar
Solution Explorer: solution explorer list the project name (namespace), program and
supporting files and folders.
Properties Window: properties window list the properties and events of the selected control
or form.
Tool Box: toolbox contains all types of controls like button, textbox, list box, container, menu
& toolbars etc.
Server Explorer: Server explorer list the database connection and database details.
Form/Class/Web Page: this place is actually user interface to design and code for the
specific application, if we work with windows application form will be user interface to design
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
3
and code, for console application class code will be there and for web application web page
will be in the centre to work with it.
Menu Bar: Menu Bar contains several options to do many operation related to development.
Tool Bar: Toolbar contains the short cut of most usable option to support development and
execution of the application.
Version 1.0: Released in 2002 with the Visual Studio .NET integrated development
environment. In version 1.0, all development — whether Windows-based or Web-based, and
regardless of the language — was
integrated into Visual Studio. Prior to the release of .NET, each Microsoft
development tool was a separate product.
The object-oriented language C# was created as part of .NET. Visual
Basic was completely revamped to be object oriented. Many Visual
Basic developers felt betrayed, and Microsoft has had a hard time convincing
them to make the leap.
Data access was greatly simplified with ADO.NET, and ASP.NET was
introduced for developing Web applications. Even though these technologies
share the same names as their predecessors (ADO and ASP), the
resemblance stops there. Like all .NET technologies, ADO.NET and ASP.
NET is object oriented.
Version 1.1:
Released in 2003 with Visual Studio .NET 2003. With version 1.1 of .NET, many 1.0 features
that either weren’t ready yet (such as the Compact Framework for devices such as the
PocketPC) or were available separately from Visual Studio (such as ASP.NET) were
completely integrated into Visual Studio .NET 2003. Version 1.1 was more stable and more
widely accepted. During this time, the Microsoft .NET brand became diluted from overuse.
Version 2.0:
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
4
Released in October 2005 with Visual Studio 2005. In the two years between the release of
versions 1.1 and 2.0, the dot-net community as the collective of .NET developers is often
called — busily wrote applications that demonstrated how powerful .NET could be. Microsoft
listened, and many of the suggestions for ways to extend .NET, which were written about in
articles on Web sites such as www.gotdotnet.com and www.4guysfromrolla.com, were
implemented as new features in the 2.0 version of .NET
Version 3.0:
Windows Presentation Foundation (WPF): Gave developers the capability to create much
richer applications by providing better controls. It helped separate the user interface (UI) from
the business logic. It also assisted developers who wanted a consistent UI between desktop
applications and Web-based applications.
Windows CardSpace: This security framework helped users to manage identities that can
be used in transactions such as Web site logins.
Version 3.5:
Released in October 2007 with Visual Studio 2008. Version3.5 builds incrementally on
version 3.0. In addition, it adds the following: Language Integrated Query (LINQ) Integrated
use of Asynchronous JavaScript and XML (AJAX) Full support for WF, WCF, and WPF
Version 4.0: Released in April 2010 with Visual Studio 2010. Version 4.0 builds on version
3.5 and adds the following:
Parallel processing
Version 4.5:
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
5
Visual Studio 2012 Beta was released on February 1, 2012 and can be downloaded from
the product's home page (Microsoft Website).
The source code of Visual Studio 2012 consists of approximately 50 million lines of code.
The completion of final build of Visual Studio 2012 was announced on August 1, 2012 with
official launch event took place on September 12, 2012.
The Microsoft .NET Framework is a software framework that can be installed on computers
running Microsoft Windows operating systems.
.NET framework provides an environment for building, deploying and running web services
and other applications, .Net framework is one of the tools provided by the .NET infrastructure
and tools component of the .NET platform, .NET platform provides a new environment for
creating and running robust, scalable and distributed applications over the web. Here is the
picture to explain .NET framework:
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
6
.NET framework shows that a programmer can write a program in any language that will be
translated into MSIL and then CLR will convert it to the native language from where we can
get the output of the program.
1.5 Common Language Runtime (CLR) is the back bone for the .NET Framework, it is
responsible for loading and running C# programs, Base classes provide basic data types,
collection classes and other general classes for use by C# and other .NET Languages. It
support cross language interoperability.
Services of CLR:
Components of CLR
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
7
1.6 Framework Base Classes: .NET supplies a library of base classes that we can use to
implement application quickly. We can use them by inheriting in the program or by creating
object and calling their methods. By using System namespace in the programs we can use
most the functionality including:
.NET framework allows us to implement following types of application for user and program
interfaces:
✓ Console Application
✓ Windows Application
✓ Web Application
In this book we will be covering first two applications with some real time examples.
Managed Code: As we know that the CLR is responsible for managing the execution of code
compiled for the .NET platform. The code that satisfies the CLR at run time in order to
execute is referred to as managed code. Compilers that are compatible to the .NET platform
generate managed code. C# compiler generates managed code (Intermediate language) and
then converted to native machine code by JIT compiler.
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
8
C# Program
Compiler
EXE Code
Verifier Test
JIT Compiler
Runtime Manager
Output
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
9
2.1 Introduction to C#
C#
Java
1996
ANSI C 1995
C++ 1987
C
1983
1972
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
10
2. 2 C# Features:
CTS type:The basic predefined types recognized by C# are not intrinsic to the
language but are part of the .NET framework.
For example, when we declare an int in C#, what we are
actually declared is an instance of a .NET struct, System.Int32. this may sound like a
small point, but it has a profound significance, it meanse that we are able to treat all
the primitive data types syntactically as if they were classes that support certain
methods.
For examples, to convert an int i to a string:
string s=i.ToString( );
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
11
Integer Types:
Name CTS Type Description
Decimal Type:
Name CTS Type Description
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
12
Boolean Type:
Name CTS Type Description
Chracter Type:
Name CTS Type Description
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
13
}
}
Output:
Hi Rahul
Integer values are 10, 20, 30
Program description:
System: System is the root namespace of C# having all the inbuilt classes and interfaces.
it just like the package in java.
Namespace: namespace is the way to organize related classes and other types, unlike a
file of a component; namespace is a logical, rather than a physical grouping. When we
define a class in a C# file, we can include it within a namespace definition. Later, when we
define another class that performs related work in another file, we can include it within the
same namespace. It is just like project name in visual basic. By default C# project name is
the namespace of the program. Here consoleAppl1 is the console application project
name.
Class Sample: sample is just the user defined class having the main method.
Public: is the access specifier which helps the function to be accessed from outside the
namespace.
Static: keyword allows the function to be called without creating the object of the class.
Void: is just a null data type specifying here that main is not returning anything from it.
String is an inbuilt reference type of data type, can be used to declare variable for
keeping string in it.
Executing C# program:
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
14
Numerical types of .NET support MaxValue and MinValue properties that provide
information regarding the range a given type can store. Here is an example showing
additional members.
using System;
namespace MyConsoleapplication
{
class maxminkey
{
static int Main(string[] args)
{
Console.WriteLine();
Show_Data_Functionality();
Console.ReadLine();
return -1;
}
static void Show_Data_Functionality()
{
Console.WriteLine("Data Type Functionality:");
Console.WriteLine("Max of int: {0}", int.MaxValue);
Console.WriteLine("Min of int: {0}", int.MinValue);
Console.WriteLine("Max of double: {0}", double.MaxValue);
Console.WriteLine("Min of double: {0}", double.MinValue);
Console.WriteLine("double.Epsilon: {0}", double.Epsilon);
Console.WriteLine("double.PositiveInfinity: {0}", double.PositiveInfinity);
Console.WriteLine("double.NegativeInfinity: {0}", double.NegativeInfinity);
Console.WriteLine("bool.FalseString: {0}", bool.FalseString);
Console.WriteLine("bool.TrueString: {0}", bool.TrueString);
Console.WriteLine();
}
}
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
15
2.5 Enumerations:
An enumeration is a user-defined integer type. When we declare an enumeration, we specify
a set of acceptable values that instances of that enumeration can contain. Not only that, but
we can give the value user-friendly names. C++ does support enumerations (or enums ), but
C# enumerations are far more powerful than their C++ counterparts.
Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Enumtest
{
// enumeration definition
public enum timeofday
{
morning = 0, afternoon = 1, evening = 2
}
static void Main(string[] args)
{
greeting(timeofday.morning);
Console.ReadLine();
}
public static void greeting(timeofday td)
{
switch(td)
{
case timeofday.morning: Console.WriteLine("Good Morning");
break;
case timeofday.afternoon: Console.WriteLine("Good afternoon");
break;
case timeofday.evening: Console.WriteLine("Good Evening");
break;
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
16
}
}
}
}
Here we are just discussing the syntax/simple example of the flow controls, later in
console application unit all these controls will be used with real examples.
1. Conditional statement
If statement: is used to check one or more condition.
Syntax:
If (condition)
Statment1;
Else
Statemaent 2;
Example:
If(a>b)
Console.writeLine(“a is greater that b”);
else
Console.writeLine(“a is not greater than b”);
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
17
break ;
default:
Console.writeLine(“value not from the cases”);
break;
}
2. Looping statement
For loop
Example:
int 1;
for(i=1;i<=100;i++)
{
Console.writeLine(“i=”+i);
}
While loop
Example:
int i=1;
While(i<=100)
{
Console.writeLine(“i=”+i);
I++;
}
Do-while loop: do-while loop is the only exit control loop, rest all are entry control.
Example:
Int i=20;
do{
Console.writeLine(“i=”+i);
i--;
}while(i>0);
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
18
Foreach statement: The foreach statement is similar to for loop but implemented
differently. It enables us to iterate the element in array and collection classes such as
List and HashTable.
Syntax:
foreach(type variable in expression)
{
Body of the loop;
}
Example:
Program for printing an array values using foreach loop:
Using System;
Class Test1
{
public static void Main( )
{
int [ ] list={1,2,3,4,5,6,7,8,};
foreach(int n in list)
{
Console.writeLine(“List=”+n);
}
Console.readLine(); // to hold the output
}
}
Here console.readLine() wait for the key press or input, but input is not assigned in any
variable. Finally it will hold the output of the program till we are not pressing any key, in
C/C++ getch() function is used for the same purpose.
3. Jump statement
Goto statement: goto statement was removed from java but introduce here in C# like
C/C++, which help to jump from one statement to another statement.
Example:
Using System;
Class Test2
{
public static void Main( )
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
19
{
int i=1;
Show:
Console.writeLine(“value “+i)
i++;
if(i<10)
goto Show;
Console.writeLine();
}
}
Using System;
Class Test3
{
Public static void Main( )
{
int i=1;
While(i<=100)
{
Console.writeLine(“i=”+i);
i++;
If(i==51)
Break;
}
}
Using System;
class Test4
{
public static int Main( )
{
for(int i=1;i<=50;i++)
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
20
{
Console.writeLine(“i=”+i);
if(i<20)
continue;
Console.writeLine(“<20”);
}
Console.readLine();
return 0;
}
}
2.7 Operators:
All the operators in C# are same as in C/C++, here all types of operators are:
1. Arithmetic operator
Example: + - * / %
2. Relational operator
Example: < <= > >= ==
!=
3. Logical operator
Example: && || ! & | ^
4. Assignment operator
Example: =
5. Increment and decrement operator
Example: ++ --
6. Conditional operator
Example: ?:
7. Bitwise operator
Example: & | ^ ~ << >>
8. Special operator
Example: is as typeof sizeof new .(dot)
checked unchecked
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
21
Comment statements are same as in C++, it uses both the single and multiple Line
comments statement.
Multi-Line Comment:
*/
2.9 Type Casting: Converting data from one type to another type, especially from big size to
small size variable.
Implicit type conversion: implicit type casting is done without losing any data, it as an
automatic type conversion from a small variable to a big variable
Example:
short s=15;
int n=s; //conversion from short to int
long x=n; //conversion from int to long
Explicit type casting: value from a big size variable cannot be assigned to a smaller size
variable implicitly, here we can use explicit conversion but it may result in loss of data.
Example:
int n=50;
byte b=(byte)n; //Casting from int to byte
float f=120.01f;
int y=(int)f; //Casting from float to int
Boxing is the conversion of a value type (int, long, float, …….) to an object type, we need to
convert because from a value type variable we cannot call any method according to oops.
Example:
int n=100;
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
22
OR
Example:
int n=100;
In boxing operation, values of the variable and object are independent of each other; object
value resides on heap, while value type variable values resides on stack.
Let's look at the incoming array of string data. Now we want to update our application to
process any possible command-line parameters using a C# for loop.
//Program4.cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Mycommandline
{
class Program4
{
static int Main(string[] args)
{
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
23
Here, we are checking to see whether the array of strings contains the number of items
using the Length property of System.Array.
C:\>cd CSharp
C:\CSharp>csc Program4.cs
Microsoft (R) Visual C# 2010 Compiler version 4.0.30319.1
Copyright (C) Microsoft Corporation. All rights reserved.
C:\CSharp>
As we loop over each item in the array, its value is printed to the console window.
We can use an alternative to the standard for loop. We may iterate over an incoming string
array using the C# foreach keyword:
foreach(string a in args)
Console.WriteLine("Arg: {0}", a);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyFirstCSharpCode
{
class Program5
{
static int Main(string[] args)
{
Console.WriteLine();
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
24
Output is
C:\CSharp>csc Program5.cs
Microsoft (R) Visual C# 2010 Compiler version 4.0.30319.1
Copyright (C) Microsoft Corporation. All rights reserved.
Arg: Program5
Arg: argA
Arg: argB
Arg: argC
C:\CSharp>
While in the real world, the user supplies the command-line arguments, we may want to
specify command-line argument during the development cycle.
To specify the arguments with Visual Studio 2010, double-click the Properties icon from
Solution Explorer.
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
25
Then, select the Debug tab on the left side. After that we can specify values using the
Command line arguments text box.
System.Environment Class: The Environment class allows us to obtain a number of details related
to the operating system via various static members.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyConsoleApp
{
class Program
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
26
{
static int Main(string[] args)
{
Console.WriteLine("System.Environment Class");
Console.WriteLine();
ShowEnvDetails();
Console.ReadLine();
return -1;
}
static void ShowEnvDetails()
{
foreach (string drv in Environment.GetLogicalDrives())
Console.WriteLine("Drive: {0}", drv);
Console.WriteLine("OS: {0}", Environment.OSVersion);
Console.WriteLine("# of processors: {0}",
Environment.ProcessorCount);
Console.WriteLine(".NET Version: {0}", Environment.Version);
}
}
}
System.Environment Class
Drive: C:\
Drive: D:\
Drive: E:\
Drive: F:\
Drive: Y:\
Drive: Z:\
OS: Microsoft Windows NT 6.0.6001 Service Pack 1
# of processors: 2
.NET Version: 4.0.30319.1
2.12 Structure
A Structure is one of the ways to modularize the program, a C# structure can hold data and
member functions as well like a class. It is a familiar and convenient way to encapsulate
different variables and the methods in a structure. But it cannot be inherited like a class.
Structure is a value type which is stored at the stack, while a class is a reference type which
is stored at the heap data structure.
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
27
A structure’s variable can be created like any other variables of value types, and value can be
assigned using (dot) operator.
using System;
namespace ConsoleApplication4
{
struct Item
{
public int sno;
public string name;
public float price;
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
28
}
class struct1
{
public static void Main()
{
Item pen;
Console.WriteLine("Enter sno, name and price:");
pen.sno = int.Parse(Console.ReadLine());
pen.name = Console.ReadLine();
pen.price = int.Parse(Console.ReadLine());
Console.WriteLine("________Items Detail_____________");
Console.WriteLine("SNo =" + pen.sno);
Console.WriteLine("Name =" + pen.name);
Console.WriteLine("Price =" + pen.price);
Console.ReadLine();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication4
{
struct Item2
{
int sno;
string name;
float price;
public Item2(int s,string nm,int p) //constructor
{
sno = s; name = nm; price = p;
}
public void accept()
{
Console.WriteLine("Enter sno, name and price:");
sno = int.Parse(Console.ReadLine());
name = Console.ReadLine();
price = int.Parse(Console.ReadLine());
}
public void show()
{
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
29
Console.WriteLine("__________Items Detail______");
Console.WriteLine("SNo =" + sno);
Console.WriteLine("Name =" +name);
Console.WriteLine("Price =" +price);
}
}
class structTest
{
public static void Main()
{
Item2 pen=new Item2();
pen.accept();
pen.show();
Console.ReadLine();
}
}
}
Object of a structure with method must be created by new operator, it calls the constructor.
Item2 pen=new Item2();
Methods of a structure can be called similar to a class method.
pen.show();
Chapter #3: Arrays, Methods and string
3.1 Array
Array is a linear data structure, which allows us to store data of the same type in a sequential
manner. In C# array can be created using new operator dynamically. Like java, in C# also
array can be created of three types:
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
30
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApp1
{
class Class1
{
public static void Main( )
{
int n,i,j,temp;
int[] list;
Console.WriteLine("Enter the size of an array");
n=int.Parse(Console.ReadLine());
list = new int[n];
Console.WriteLine("Enter " + n + " Elements");
for (i = 0; i < n; i++)
{
list[i] = int.Parse(Console.ReadLine());
}
// Sorting process
for (i = 0; i < n - 1; i++)
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
31
{
for (j = i + 1; j < n; j++)
{
if (list[j] < list[i])
{
temp = list[j];
list[j] = list[i];
list[i] = temp;
}
}
}
//printing the array's elements
for (i = 0; i < n; i++)
{
Console.WriteLine("list[" + i + "]=" + list[i]);
}
Console.ReadLine();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class Class2
{
public static void Main()
{
int m,n, i, j;
int[,] matrix;
Console.WriteLine("Enter the number of rows");
m = int.Parse(Console.ReadLine());
Console.WriteLine("Enter the numer of columns");
n = int.Parse(Console.ReadLine());
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
32
Console.ReadLine();
}
}
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
33
3.1.2 The methods of the System.Array class: In C#, every array we create is
automatically derived from the System.Array class. This class defines a number of methods
and properties that can be used to manipulate arrays more efficiently.
We can call these methods from array name just with the help of dot operator.
Example:
int [ ] list = new int[5];
int m=list.Max( );
Methods Description
Property Description
using System;
using System.Collections.Generic;
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
34
using System.Linq;
using System.Text;
namespace ConsoleApp3
{
class arraymethods
{
public static void Main()
{
int n, i, j;
int[] list;
Console.WriteLine("Enter the size of an array");
n = int.Parse(Console.ReadLine());
list = new int[n];
Console.WriteLine("Enter " + n + " Elements");
for (i = 0; i < n; i++)
{
list[i] = int.Parse(Console.ReadLine());
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
35
j=list.Length;
Console.WriteLine("Length of the list=" + j);
Console.ReadLine();
}
}
}
3.2 ArrayList
Here we are creating an object of N size; but if we want to put more that N elements to the list
we can do it, because arraylist expands its size according to the use, that we will see in the
following program. And if we don’t give the size, by default it creates the object with 16 sizes.
alist.add(“Bangalore”);
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
36
alist.add(“2012”);
OR
alist.add(Console.ReadLine() ); // accepting data from keyboard
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace arraylisttest
{
class Testarraylist
{
public static void Main()
{
ArrayList al = new ArrayList(5);
Console.WriteLine("Enter 10 numbers");
for (int i = 0; i < 10; i++)
{
al.Add(Console.ReadLine());
}
//sorting the elements of the list
al.Sort();
Console.WriteLine("Elements in sorted order");
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
37
}
}
Output:
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
38
Methods can be implemented within the scope of classes or structures and prototyped within
interface types. Methods may be written with various keywords (internal, virtual, public,
private, protected, new, static ) to qualify their behavior.
While the definition of a method in C# is straightforward, there are a handful of keywords that
we can use to control how arguments are passed to the method.
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
39
Output parameters must be assigned by the method being called (and therefore are
out passed be reference). If the called method fails to assign output parameters, we
are issued a compiler error.
The value is initially assigned by the caller and may be optionally reassigned by the
ref called method (as the data is also passed by reference). No compiler error is
generated if the called method fails to assign a ref parameter.
The default manner in which a parameter is sent into a function is by value. In other words, if
we do not mark an argument with a parameter-centric modifier, a copy of the data is passed
into the function. Exactly what is copied will depend on whether the parameter is a value type
of a reference type.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Mymethods
{
class Program
{
static int add(int x, int y)
{
int ans = x + y;
x = 100; y = 200;
return ans;
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
40
Output is:
Numerical data is value types. So, if we change the values of the parameters within the
scope of the member, the caller is unaware, given that we are changing the values on a copy
of the caller's data:
In this section, we are dealing with output modifier. Methods that have been defined to take
output parameters (via the out keyword) are under obligation to assign them to an
appropriate value before exiting the method.
To demonstrate, here is an alternative version of the add() method that returns the sum of
two integers using the out modifier while the physical return value of this method is now void.
namespace Mymethods
{
class Program
{
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
41
Calling a method with output parameter also requires the use of the out modifier. Local
variables passed as output variables are not required to be assigned before use.
The example above is just for demonstration purpose, and actually we have no reason to
return the value of our summation using an output parameter. But the out modifier does
serve a very useful purpose: it allows the called to obtain multiple return values from a
single method invocation.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Mymethods
{
class Program
{
static void GetMultipleValues(out int a, out string s, out bool b)
{
a = 2010;
s = "string as one of multiple return values";
b = true;
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
42
Output is:
Methods that define output parameters must assign the parameters to a valid value before
exiting the methods. So, the following method will result in a compiler error, as the integer
parameter has not been assigned within the method scope:
Reference parameters are necessary when we want to allow a method to operate on various
data points declared in the caller's scope such as sorting or swapping routine. Here is the
distinction between output and reference parameters:
• Output parameters do not need to be initialized before they passed to the method. It's
because the method must assign output parameters before exiting.
• Reference parameters must be initialized before they are passed to the method. It's
because we are passing a reference to an existing variable. If we don't assign it to an
initial value, that would be the equivalent of operating on an unassigned local variable.
Let's look at the following example which uses ref keyword by way of a method that swaps
two strings:
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
43
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Mymethods
{
class Program
{
static void SwapStrings(ref string s1, ref string s2)
{
string temp = s1;
s1 = s2;
s2 = temp;
}
The caller has assigned an initial value to local string data, s1 and s2. Once the call to
SwapStrings() returns, s1 now contains the value Dijkstra while s2 holds the value Edsger.
C# supports the use of parameter arrays. To understand the role of the params keyword,
we must understand how to manipulate C# arrays.
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
44
The params keyword allows us to pass into a method a variable number of parameters of the
same type as a single logical parameter. Arguments marked with the params keyword can
be processed if the caller sends in a strongly typed array or a comma-delimited list of items.
Assume we wish to create a function that allows the called to pass in any number of
arguments and return the calculated average. If we were to prototype this method to take an
array of double, this would force the caller to first define the array, then fill the array and
finally pass it into the method. However, if we define Avarage() to take a params of integer
data types, the caller can simply pass a comma-delimited list of doubles. The .NET runtime
will automatically package the set of doubles into an array of type double behind the
scenes:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Mymethods
{
class Program
{
static double Average(params double[] values)
{
Console.WriteLine("{0} doubles", values.Length);
double sum = 0;
if (values.Length == 0)
return sum;
for (int i = 0; i < values.Length; i++)
sum += values[i];
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
45
Console.ReadLine();
}
}
}
Output is:
5 doubles
Average of data = 3
5 doubles
Average of data = 81.8
0 doubles
Average of data = 0
The method Average() has been defined to take a parameter array of doubles. What this
method is actually saying is "Send me any number of doubles and I'll calculate the
average." So, we can call the method in any of the ways shown above example.
Here we are covering string in short to just test the string classes and its methods.
string is a class that is specifically designed to store a string and allow a large number of
operations on the string, also because of the importance of this data type, C# has its own
keyword and associated syntax to make it particularly easy to manipulate strings using this
class.
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
46
Split( ) splits the string into an array of substring, break occurs when a
given character occurs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication4
{
class Class2
{
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
47
Console.ReadLine();
}
}
}
Building Strings:
As we know string is a class that implements a large number of very useful methods.
However, the string class has a shortcoming that makes it very inefficient for making
repeated modification to a given string; StringBuilder class allows operations like appending,
inserting, replacing character or substring to a given string.
StringBuilder defines methods that allow us to replace or format segments. To use this type,
we need to import the proper namespace:
using System.Text;
When we call members of StringBuilder, we are directly modifying the object's internal
character data instead of obtaining a copy of the data in a modified format. When we create
an instance of the StringBuilder, we can supply the object's initial startup values via one of
many constructors. Let's look at the code which shows the usage of StringBuilder.
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
48
As we see, we are appending to the internal buffer, and are able to replace (or remove)
characters. By default, a StringBuilder is only able to hold a string of 16 characters or less.
But this initial value can be changed via an additional constructor argument.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyFirstCSharpCode
{
class Programstr
{
static int Main(string[] args)
{
Console.WriteLine();
Show_StringBuilder_Functionality();
Console.ReadLine();
return -1;
}
static void Show_StringBuilder_Functionality()
{
StringBuilder sb = new StringBuilder("Simplicity, ");
sb.AppendLine(" Is the best policy, ");
sb.AppendLine("become simple!");
sb.Append("\n");
sb.AppendLine("C# Programmer");
Console.WriteLine(sb.ToString());
sb.Replace("!", ".");
Console.WriteLine(sb.ToString());
Console.WriteLine("SB has {0} chars.", sb.Length);
Console.WriteLine();
}
}
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
49
A class is a user-defined data type that is composed of members (member variables and
member functions) such as data, constructors, properties, methods, events, and so forth.
The set of field data represents the state of a class instance (object). By grouping data and
related functionality in a class definition, we are able to modul our program after entities in the
real world.
In .NET by default, all the classes will be under the namespace, the project name we give
during the staring of the application that project name will become the namespace; a
namespace is a collection of classes that means we can write many classes in the same
namespace.
Here all examples are given in console application but if we work with windows and web
application then also it will be the same, there each form or page represents a class.
class student
{
public string name;
public int age;
public void Show( )
{
}
}
The member variables are declared using public access modifier. Public members of a class
are directly accessible once an object (instance of a given class) of this type has been
created.
using System;
namespace TestProject
{
class student
{
public string name;
public int age;
public void Show()
{
Console.WriteLine("{0}'s age is {1} Years.", name, age);
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
50
st.Show();
Console.ReadLine( );
}
}
}
Objects must be allocated into memory using the new keyword. If we don't use the new
keyword and attempt to use our class variable in a subsequent code, we'll get a compiler
error, something like “Use of unassigned local variable”:
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
51
A constructor is a special method of a class that is called directly when creating an object
using the new keyword. However, unlike a normal method, constructors never have a return
type (not even void and are always named identically to the class they are constructing.
Example:-
class student
{
public string name;
public int age;
public student( ) //constructor
{
name=”John”;
age=22;
}
}
Default Constructor
Every class is provided with a default constructor that we may redefine. A default
constructor never takes argument, by definition. Beyond allocating the new object into
memory, the default constructor ensures that all field data is set to an appropriate default
value. If we can not satisfied with these default assignments, we may redefine the default
constructor to meet our needs.
using System;
namespace TestProject
{
class student
{
public string name;
public int age;
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
52
Console.ReadLine();
}
}
}
Custom Constructor
In general, classes define additional constructors besides the default. We provide the object
user with a simple and consistent way to initialize the state of an object directly at the time of
creation. In the following example with three class constructors:
using System;
namespace TestProject
{
class student
{
public string name;
public int age;
public student()
{
name = "John";
age = 24;
}
public student(string n)
{
name = n;
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
53
Console.ReadLine();
}
}
}
What makes one constructor different from another is the number of and type of constructor
arguments. So, the student class has overloaded the constructor to provide a number of
ways to create the object at the time of declaration.
C# supports this keyword which provides access to the current class instance. One of uses
of this keyword is to resolve scope ambiguity, which can arise when an incoming parameter
is named identically to a data field of the type as shown in the following example:
class student
{
public string name;
The code will compile just fine, but the value of the name filed is an empty string. Instead the
code should be as follow:
class student
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
54
{
public string name;
If there is no ambiguity, we are not required to use this keyword when a class wants to
access its own data or members. For example, if we rename the string data member to
stud_name, the use of this is optional as there is no longer a scope of ambiguity:
class student
{
public string stud_name;
A C# class can define any number of static members using static keyword. The static
members can be invoked directly from the class level rather than a type instance.
Console obj;
If we write the code, we get an error message: Cannot declare a variable of static type
System.Console.
We cannot invoke the WriteLine() method from the object level, either.
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
55
Static members are items that are deemed to be so commonplace that there is no need to
create an instance of the type when invoking the member. While any class can define static
members, they are most commonly found within utility classes such as System.Console,
System.Math, System.Environment, or System.GC, and so on.
Let's see one example of static members, which are called from class name not from the
object.
Example :-
class Test
{
public static short n;
public static void show()
{
Console.WriteLine("Class variable's value");
Console.WriteLine("N=" + n);
}
}
Class staticTest
{
static void Main()
{
Test.n=5;
Test.show();
Console.ReadLine();
}
}
If we attempt to use nonstatic class data or call a nonstatic method of the class within a static
member's implementation, we'll get compile-time errors.
Static data is just a variable declared with static keyword; it doesn’t take place in object like
other normal variables but will be shared by all the instances of the class.
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
56
A static constructor is a special constructor that is an ideal place to initialize the values of
static data when the value is now known at compile time such cases when we need to read in
the value from an external file or generate a random number, and so on. Here are a few
things related to the static constructors:
• A given class (or structure) may define only a single static constructor.
• A static constructor does not take an access modifier and cannot take any parameters.
• A static constructor executes exactly one time, regardless of how many objects of the
type are created.
• The runtime invokes the static constructor when it creates an instance of the class or
before accessing the first static member invoked by the caller.
• The static constructor executes before any instance-level constructors.
Example:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication4
{
class staticConst
{
static void Main()
{
ST obj1 = new ST();
ST obj2 = new ST();
ST obj3 = new ST();
obj1.show();
obj2.show();
ST.show2();
Console.ReadLine();
}
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
57
class ST
{
static short n;
int m;
static ST() //access specifier not allowed with static constructor
{
Console.WriteLine("Constructor invoked");
n = 100;
}
public ST()
{ m = 101; }
public void show()
{
Console.WriteLine("N=" + n); //printing class value
Console.WriteLine("N=" + this.m); //printing object value
}
public static void show2()
{
Console.WriteLine("Class variable's value");
Console.WriteLine("N=" + n);
}
}
When a class has been defined as static, it is not creatable using the new keyword, and it
can contain only members or fields market with the static keyword.
The class that cannot be created does not appear all that useful. However, if we create a
class that contains nothing but static members and constant data, the class has no need to
be allocated in the first place. Let's take a look at the following example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace StaticClass
{
static class TimeUtilClass
{
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
58
Because this class has been defined with the static keyword, we cannot create an instance
of TimeUtilClass using the new keyword.
Prior to .NET 2.0, the only way to prevent the creation of a class type was to either redefine
the default constructor as private or mark the class as an abstract type using the abstract
keyword:
class TimeUtilClass
{
private TimeUtilClass(){}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
59
Though these constructs are still permissible, the use of static classes is a cleaner solution
and more type-safe, given that the previous two allowed nonstatic members to appear within
the class definition without error.
A project's application class which defines the Main() method is often defined as a static
class, to ensure it only contains static members and cannot be directly created:
The idea of encapsulation is that an object's internal data should not be directly accessible
from an object instance. Rather, if the called wants to alter the state of an object, the user
does so indirectly using accessor (getter) and mutator (setter) methods. In C#, encapsulation
is enforced at the syntactic level using the public, private, internal, and protected
keywords. To demonstrate the need for encapsulation services, assume we have created the
following class definition:
class Book
{
public int Pages();
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
60
The problem with public field data is that the item has no ability to intrinsically understand
whether the current value to which they are assigned is valid with regard to the current rule of
the system. As we know, the upper range of a C# int is quite large (2,147,483,647).
Therefore, the compiler allows the following assignment:
Even though we don't have overflow error, it should be clear that a pictureBook with a
1,500,000,000 pages is unreasonable. If our system has rule that limits the number of pages
to 1000, we are at a loss to enforce this programmatically. Because of this, public field
typically have no place in a production-level class definition.
Encapsulation provides a way to preserve the integrity of an object's state data. Rather than
defining public fields, we should get in the habit of defining private data, which is indirectly
manipulated using one of two main techniques:
In addition to those, C# provides the readonly keyword, which also delivers a level of data
protection. Well-encapsulated class should hide the details of how it operates from the
outside. This is often referred as black box programming. The beauty of this approach is
that an object is free to change how a given method is implemented under the hood. It does
this without breaking any existing code making use of it, provided that the signature of the
method remains constant.
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
61
4.9 Polymorphism: one name multiple form, it can be achieved in two ways:
Method overloading:
Method overloading is a process to define multiple methods with the same name in a class
with different number and different types of arguments.
Example-
class shapes
{
public double area(short r)
{
return 3.14 * r * r;
}
public int area(short l,short b)
{
return l*b;
}
public double area(float b,float h)
{
return 0.5*b*h;
}
public float area(float s)
{
return s * s;
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
62
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication4
{
class poly
{
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
63
case 5: Environment.Exit(0);
break;
default: Console.WriteLine("Invalid option ! Try again");
break;
}
} while (opt != 5);
}
}
class shapes
{
public double area(short r)
{
return 3.14 * r * r;
}
public int area(short l,short b)
{
return l*b;
}
public double area(float b,float h)
{
return 0.5*b*h;
}
public float area(float s)
{
return s * s;
}
}
}
4.10 Properties
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
64
Though we can encapsulate field data using traditional get and set methods, .NET prefers to
enforce data protection using properties. First of all, note that properties always map to
accessor and mutator methods in terms of CIL (Common Intermediate Language) code.
Thus, as a class designer, we're still able to perform any internal logic necessary before
making the value assignment.
Properties are the concept to set and get data of an object, its shortcut to accessor methods.
Example-
class Student
{
string name;
public string prop
{
set
{
name = value;
}
get
{
return name;
}
}
}
class prop1
{
static void Main(string[] args)
{
Student st = new Student();
st.prop = "Eklavya";
Console.WriteLine("Hello "+st.prop);
Console.ReadLine();
}
}
Output
Hello Eklavya
Indexers
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
65
Indexers are location indicators and are used to access class objects. Just like accessing
elements in an array. They are useful in cases is a container for other objects. An indexers
look like a properties and is written the same way as property is written. But with two
differences:
The indexer is implemented through get and set accessor for the [ ] operator.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace indexerTest
{
class test
{
object[] obj = new object[5];
public object this[int index]
{
get{
if(index <0 && index >=obj.Count())
{
return null;
}
else
{
return (obj[index]);
}
}
set{
obj[index]=value;
}
}
}
class Program
{
static void Main(string[ ] args)
{
object[ ] list =new object[5];
list[0] = "26";
list[1] = "Jan";
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
66
list[2] = "2012";
foreach (object item in list)
Console.Write(" "+item);
Console.ReadLine();
}
}
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
67
5.1 Inheritance
Inheritance is one of the best features of object oriented programming (OOP), which allows
us to reuse the features of an existing class to a new class; it reduces the complexity and the
length of a program.
In other words, Inheritance is one of the pillars of OOP that facilitates code reuse.
2. Multilevel inheritance
3. Hierarchical inheritance
4. Multiple inheritance
5. Hybrid inheritance
5.1.1: Single level inheritance: - in single level inheritance one class inherits another class.
Here the class which inherits called sub class or child class and the class which is inherited
by child called parent or base class.
Super/base/parent class
Class A
Class B
Sub/derived/child class
Syntax:
class A
{
------------
}
class B : A
{
------------
}
Example-
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
68
namespace ConsoleApplication
{
class single
{
static void Main()
{
B obj = new B();
obj.getab();
obj.show();
Console.ReadLine();
}
}
class A
{
public int a, b;
public void getab()
{
Console.WriteLine("Enter the value of a & b");
a = int.Parse(Console.ReadLine());
b = int.Parse(Console.ReadLine());
}
}
class B : A
{
int c;
public B()
{
c = 100;
}
public void show()
{
Console.WriteLine("a=" + a);
Console.WriteLine("b=" + b);
Console.WriteLine("c=" + c);
}
}
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
69
Syntax-
class A
{
------------
}
class B : A
{
------------
}
class C : B
{
------------
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
70
Syntax-
class Item
{
------------
}
class Processor : Item
{
------------
}
class RAM : Item
{
------------
}
Example:-
class Item
{
public int code;
public int price;
public string name;
public Item(int c, int p, string nm)
{
code = c;
price = p;
name = nm;
}
public void show()
{
Console.WriteLine("Code :" + code);
Console.WriteLine("Price :" + price);
Console.WriteLine("Name :" + name);
}
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
71
class Processor:Item
{
string model,speed;
public Processor(int c, int p, string nm, string mod,string spd) : base(c, p, nm)
{
model = mod;
speed=spd;
}
public void display()
{
show();
Console.WriteLine("Model :" + model);
Console.WriteLine("Speed :" + speed);
}
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
72
}
}
Implementation of interfaces
interface Addition
{
int add( );
}
interface Multiplication
{
int mult( );
}
class Computation : Addition , Multiplication
{
int x, y;
public Computation(int a, int b)
{
x=a; y=b;
}
public int add( )
{
retrun (x+y);
}
public int mult( )
{
return (x* y);
}
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
73
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
74
5.1.5: Hybrid Inheritance: hybrid inheritance doesn’t have any specific picture, because a
hybrid inheritance can be achieved by using multiple types of inheritance, in general it is
rarely used.
Here we have two different shape but both of the same hybrid type.
Since we are using interface here in inheritance, we must discuss about it.
5.2 Interfaces:
• A class can implement multiple interfaces. In contrast, a class can inherit from only a
single class.
• Interface members are all implicitly abstract. In contrast, a class can provide both
abstract members and concrete members with implementations.
• Structs can implement interfaces. In contrast a struct cannot inherit from a class.
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
75
Example of an Interface:-
interface Addition
{
int add( );
}
Extending interfaces
Ex1:
interface A
{
void show();
}
interface B:A
{
void display();
}
----------------------------------------------------------------------
Ex2:
interface A
{
---
}
interface B
{
---
}
interface C : A , B //multiple inheritance
{
---
}
Implementing Interface:
interface can be implemented in a class
Ex-
interface A
{
void show( );
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
76
class B : A
{
Class visibility is used to decide which parts of the system can create class objects.
A C# class can have one of two visibility modifiers public or internal, by default all class are
internal, that means the class can be accessible only from the same assembly.
But if you make a class public it can be accessible from outside assembly as well.
Class member’s visibility: class members can have any one of the five modifiers. When no
modifier is specified it defaults to private accessibility.
1. public
2. private
3. protected
4. internal
5. protected internal
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
77
Here in this example, super and sub both the classes are having same named function
“Display”, to implement overriding in super class function is written with virtual keyword and in
sub class function is written with override keyword.
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
78
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
79
But if we have to hide base class method by sub class method without virtual, we can use
new operator with sub class method.
Ex-
class A
{
public void show()
{
Console.WriteLine(“A class”);
}
}
class B:A
{
public new void show()
{
Console.WriteLine(“Class B”);
}
}
Abstract Method:
it cannot have definition/implementation
it must be defined in non-abstract sub class
it can be declared only in abstract classes
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
80
Ex-
abstract class A
{
abstract void show( );
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
81
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
82
Here in this example operator + is a function which will be called automatically when we write
two objects with + operator to add, and it returns an object after addition that’s why the return
type is Test which is the class name.
class complex
{
double real, imag;
public complex()
{
real = 0.0;
imag = 0.0;
}
public void accept()
{
Console.WriteLine("Enter real part");
real = double.Parse(Console.ReadLine());
Console.WriteLine("Enter imaginarypart");
imag = float.Parse(Console.ReadLine());
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
83
class Program
{
static void Main(string[] args)
{
complex a, b, c;
a = new complex();
b = new complex();
c = new complex();
Console.WriteLine("Addition of 2 complex number using operator overloading");
Console.WriteLine("-------------------------------------------------------");
Console.WriteLine("First complex number");
a.accept();
Console.WriteLine("Second complex number");
b.accept();
c = a + b; //calling operator + function of complex class
Console.Clear();
Console.WriteLine("Sum of 2 complex numbers");
Console.Write("\t 1st complex number=");
a.display();
Console.Write("\t 2nd complex number=");
b.display();
Console.Write("sum=");
c.display();
Console.ReadLine();
}
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
84
using System;
namespace ConsoleApplication4
{
class comparison
{
static void Main()
{
Time T1 = new Time(2, 30);
Time T2 = new Time(2, 30);
if (T1 == T2) //overloading comaparison operator ==
Console.WriteLine("Both are matching");
else
Console.WriteLine("Both are different");
Console.ReadLine();
}
}
class Time
{
short h, m;
public Time(short x, short y)
{
h = x;
m = y;
}
//definition of comparison operator == function
public static bool operator ==(Time t1, Time t2)
{
if (t1.h == t2.h && t1.m == t2.m)
return true;
else
return false;
}
public static bool operator !=(Time t1, Time t2)
{
if (t1.h != t2.h && t1.m != t2.m)
return false;
else
return true;
}
}
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
85
When we overload comparison operator like ==, we need to overload its counterpart !=
operator as well, and also we need to define operator function with public static keywords.
using System;
namespace ConsoleApplication4
{
class unaryop
{
public static void Main()
{
Complex c1 = new Complex(80,90);
Console.WriteLine("Complex number before operator overloading");
c1.show();
c1++; //Calling operator ++ function
Console.WriteLine("Complex number after operator overloading");
c1.show();
Console.ReadLine();
}
}
class Complex
{
double r, im;
public Complex(double x, double y)
{
r = x;
im = y;
}
public static Complex operator ++(Complex c) //overloading ++ operator
{
Complex T = new Complex(0,0);
T.r=++c.r;
T.im=++c.im;
return T;
}
public void show()
{
Console.WriteLine("Complex No ={0} +i {1}", r, im);
}
}
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
86
After creating an object C1, C1++ statement looks like a very simple increment operation, but
it call the ++ function to add two complex number and increases both the elements real and
imaginary of a complex number.
using System;
Namespace Myproject
{
delegate int arithop(int x,int y); //delegate declaration
class Mathop
{
public static int ADD(int x,int y) //delegate method Definition.
{
return x+y;
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
87
class DelTest
{
public static void Main( )
{
//delegate instantiation
Arithop op1=new Arithop(Mathop.ADD);
Arithop op2=new Arithop(Mathop.SUB);
//invoking delegate
Console.WriteLine(“Addition=“+ op1(10,20) );
Console.WriteLine(“Substration=“+ op2(100,20) );
Console.ReadLi ne();
}
}
}
namespace ConsoleApplication1
{
delegate void printdelegate();
class dele
{
double length,breadth,height,base1,side,area;
public void rect()
{
Console.WriteLine("enter length");
length=Double.Parse(Console.ReadLine());
Console.WriteLine("enter breadth");
breadth=Double.Parse(Console.ReadLine());
area=length*breadth;
Console.WriteLine("area of rectangle="+area);
}
public void triangle()
{
Console.WriteLine("enter base");
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
88
base1=Double.Parse(Console.ReadLine());
Console.WriteLine("enter height");
height=Double.Parse(Console.ReadLine());
area=0.5*base1*height;
Console.WriteLine("area of triangle="+area);
}
class DeleTest
{
static void Main()
{
dele d = new dele();
int opt;
do
{
Console.Clear();
Console.WriteLine("ILLUSTRATION OF DELEGATES");
Console.WriteLine("1.Area of Triangle");
Console.WriteLine("2.Area of Rectangle");
Console.WriteLine("3.Area of Square");
Console.WriteLine("4.Exit");
Console.WriteLine("Enter your option:");
opt = int.Parse(Console.ReadLine());
printdelegate p;
switch (opt)
{
case 1: p = new printdelegate(d.triangle);
p();
Console.ReadLine();
break;
case 2: p = new printdelegate(d.rect);
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
89
p();
Console.ReadLine();
break;
case 3: p = new printdelegate(d.square);
p();
Console.ReadLine();
break;
case 4: Environment.Exit(0);
break;
}
}
while (opt != 4);
}
}
}
All delegate objects have natural ability to multicast. A delegate object can invoke multiple
methods, rather than a single method called multicast delegate, it is also known as
combinable delegates.
When we want to add multiple methods to a delegate object, we simply use overloaded +=
operator, rather than a direct assignment.
For example:
Invoking MD will now call both Calculate and Show methods. Delegates are invoked in the
order they are added.
The - = method removes the right delegate operand from the left delegate operand. For
example:
MD -= Calculate;
Invoking MD will now cause only Show to be invoked.
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
90
Calling += on a delegate variable with a null value works, and it is equivalent to assigning
the variable to a new value:
MultipleDelegate MD = null;
MD += show
If a multicast delegate has a non-void return type, the called receives the return value from
the last method to be invoked. The preceding methods are sill called, but their return value
are discarded. In most cases in which multicast delegates are used, they have void return
types, so this subtlety does not arise.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication4
{
class Mdelegate
{
delegate void MulticastDelegate();
public static void Main()
{
MulticastDelegate MD=new MulticastDelegate(Maths.sum);
MD+= Maths.show;
MD();
Console.ReadLine();
}
}
class Maths
{
static int a,b,c;
public static void sum()
{
Console.WriteLine("Enter Two numbers");
a=int.Parse(Console.ReadLine());
b=int.Parse(Console.ReadLine());
c=a + b;
}
public static void show()
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
91
{
Console.WriteLine("{0} + {1} = {2}", a, b, c);
}
}
}
7.3 Event:
An Event is a delegate type class member that is used by the object or class to provide a
notification to other objects that an event has occurred. The client object can act on an event
by adding an event handler to the event.
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
92
An Exception is a run time error which occurs due to some condition like in an expression
where we divide a number by zero or try to access the array index which is out of
bound or trying to use a stack which is overflowing and so on. We cannot handle these
exceptions during compile time because it won’t be reported at that time, but will terminate
the execution and give error at the run time, we can handle these exceptions at the run time
by using try, catch and finally block, finally is optional. If the statement written in the try
block will be having any exception it will be thrown to catch where the exception type will be
stored in the object of the exception class.
try
{
Statement;
}
catch (Exception_class_name object)
{
Statement;
}
Example-
try
{
c = a / b;
}
catch (Exception e)
{
Console.WriteLine("Exception " + e);
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
93
We can write statements in the try block which are suspected to report exception, here c=a/b;
suspected to report divided by zero exception, try throws that exception to catch where it
stored in the object e of Exception type, which is printed from the catch block. Even if we do
not print the exception type, our exception will be managed and our program will not
terminate abnormally, to see the exception report we usually print the exception.
Since we may face many different types of exception, C# framework 4.0 specified around 52
inbuilt classes for all different exceptions in different scenario. Most of these classes are from
System namespace.
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
94
Examples Program:-
using System;
namespace ConsoleApplication4
{
class Except
{
int a,b,c;
}
}
class ExceptionTest
{
public static void Main()
{
Except obj = new Except();
obj.accept();
obj.cal();
Console.ReadLine();
}
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
95
In this program if we accept zero for the variable b it shows the exception “ Dived by Zero
Exception”, but after accepting non zero value for the b variable it gives the desired output.
Here try and catch blocks handles one exception divided by zero and doesn’t allow the
program to terminate abnormally.
Here is an example:-
try
{
c = a / b;
list[5] = 50;
Console.WriteLine(" a/b= " + c);
}
catch (DivideByZeroException d)
{
Console.WriteLine("Exception: " + d.Message);
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine("Exception " + ex.Message);
}
Here in the try block first two statements are expected to throw two exceptions which are
handled through two catches. First catch handles the divided by zero exception and the
second one handles the array index out of range exception.
Finally block: - is the block used at the end of all catch statements and executed for sure. It
handles the exception which is not caught by any of the previous catch statement.
try
{
c = a / b;
list[5] = 50;
Console.WriteLine(" a/b= " + c);
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
96
catch (DivideByZeroException d)
{
Console.WriteLine("Exception: " + d.Message);
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine("Exception " + ex.Message);
}
finally
{
Console.WriteLine("End of the program");
}
Throwing our own exception: A user defined exception class which is possible by inheriting a
generic Exception class.
8.4 C# that will read a name from the keyboard and display it on the screen. The
program to throw an exception when the length of the name is more than 15
characters. Program to throw our own exception.
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication4
{
class MyException : Exception
{
public MyException(string str)
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
97
: base(str)
{
Console.WriteLine("user defined exception called");
}
}
class Exceptionprog
{
static void Main(string[] args)
{
int opt, number1, number2;
string name;
int[] arr = new int[5] { 10, 20, 30, 40, 50 };
do
{
Console.Clear();
Console.WriteLine("illustrating exceptions");
Console.WriteLine("1.divide by zero");
Console.WriteLine("2.array index out of range");
Console.WriteLine("3.user defined exception");
Console.WriteLine("4.exit");
Console.WriteLine("enter an option");
opt = int.Parse(Console.ReadLine());
try
{
switch (opt)
{
case 1: Console.WriteLine("enter ur no");
number1 = int.Parse(Console.ReadLine());
Console.WriteLine("enter number 2");
number2 = int.Parse(Console.ReadLine());
Console.WriteLine("the result of number1 and num2" + number1 /
(number2));
Console.ReadLine();
break;
case 2: Console.WriteLine("array value");
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
98
throw new MyException("the string length should not be more than 5 cahr");
else
Console.WriteLine("entered string is right");
Console.ReadLine();
break;
case 4: break;
}
}
catch (DivideByZeroException e)
{
Console.WriteLine("do not divide a number by zero" + e);
Console.ReadLine();
}
catch (IndexOutOfRangeException e)
{
Console.WriteLine("array indx out of range" + e);
Console.ReadLine();
}
catch (MyException e)
{
Console.WriteLine("e.msg" + e);
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine("exception caught here" + e.Message);
Console.ReadLine();
}
}
while (opt != 4);
Console.ReadLine();
}
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
99
Like java C# also supports multithreading which enable us to execute multiple part of a
program simultaneously, that part of the program may be a method having any set of
instructions. Multithreading requires using a class “System.Threading.Thread” which has
different functions for different operation on a thread.
The most primitive of all types in System.Threading namespace is Thread. This type
defines a number of methods that allow us to create new threads within the current
Application Domain. It also allows us to suspend, stop, and destroy a particular thread.
Methods/Properties Description
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
100
using System.Threading;
public class MyThread
{
public static void Thread1() //thread 1
{
for (int i = 1; i < 100; i++)
{
Console.WriteLine("Thread1 {0}", i);
}
}
public static void Thread2() //thread 2
{
for (int i = 101; i < 200; i++)
{
Console.WriteLine("Thread2 {0}", i);
}
}
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
101
{
Console.WriteLine("Before start thread");
Thread tid1 = new Thread(new ThreadStart(MyThread.Thread1));
Thread tid2 = new Thread(new ThreadStart(MyThread.Thread2));
tid1.Start();
tid2.Start();
Console.ReadLine();
}
}
A thread can be interrupted by using function like abort ( ), sleep ( ), suspend ( ) and interrupt
( ).
}
}
} //end of thread
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
102
try
{
thr.Abort();
}
catch (Exception ae)
{
Console.WriteLine(ae.Message);
}
}
}
} //end of thread 2
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
103
Console.ReadLine();
}
}
using System;
using System.Threading;
namespace ConsoleApplicatio4
{
public class MyThread
{
public static void Thread1() //thread 1
{
for (int i = 1; i < 100; i++)
{
Console.WriteLine("Thread1 {0}", i);
}
//getting priority
Console.WriteLine("Thread 1 Priority :" + Thread.CurrentThread.Priority.ToString());
}
public static void Thread2() //thread 2
{
for (int i = 101; i < 200; i++)
{
Console.WriteLine("Thread2 {0}", i);
}
Console.WriteLine("Thread 2 Priority :" + Thread.CurrentThread.Priority.ToString());
}
}
public class CallThreads
{
public static void Main() //main thread
{
Console.WriteLine("Before start thread");
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
104
Windows application give us the form like visual basic to design and then write the code for
it, this application is best suited for the desktop application and very convenient to design
attractive form by drag and drop controls from the given tool box and by using different
properties of the form.
A form represents a class and all controls taken on the form represent methods respectively
in the code. So, the form code will look same as the code we have discussed in the console
application, that’s why we are not going to discuss any coding here, but we must note it that,
we don’t have to write the method definition of any control or the class for the form, all these
appears automatically by just double clicking on the controls of the form. We can also see
the code of the form from the view code icons.
A nice database application project can be designed using windows application, .NET is
having great support of data base, it allows us to connect our program by using ADO.NET
which will be discussed in the next chapter.
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
105
3. We get start page window of visual studio which has the options to open new or existing
projects.
4. Click on the “New Project” option which opens a window with options to choose
language, application type and the project/application name.
5. From the “New Project” window choose C# language and Windows Forms Application
then enter the name of your project and then click on OK button. If we don’t enter the
name it takes by default name of the project as “WindowsFormsApplication1”.
6. After clicking on OK button, our application starts in .NET IDE (integrated development
Environment) with by default form1. Here we can design the form with controls and
properties and run the project by just clicking on the green (start debug) button or
directly by pressing F5 button.
Start page_ Microsoft visual studio’s picture is given below to help and understand the steps,
we can see new project window that is listing all languages supported by .NET framework
4.0 and all different types of applications which can be chosen according to the requirement.
If we wish to go for console application we can choose “Console Application”, for Web we
can choose “ASP.NET Web Application” and so on.
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
106
After getting the form we need to design the form using controls and its properties. But
before that we must know about the controls and its properties, most of the controls in .NET
are same as Visual Basic.
Let’s design a login form using some familiar controls like labels, textbox and buttons.
Login form is designed using 6 controls, two labels for user name and password, two
textboxes for the same and two buttons for OK and cancel. In the window we can see one
property of the password text box “PasswordChar” which is given * character which shows
when typing password, this properties allows to hide the password during input, for the rest
controls only “Text” properties are given which are visible like OK and Cancel are the values
of Text property of the Button controls.
Controls are the main tools on the toolbox to design and give action to a form; all controls
are associated with some events and properties, most of the controls have some common
properties like: name, enabled and visible. Below is a list of controls with events and
properties.
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
107
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
108
After having looked on these controls, let’s use these controls in different programs.
10.1.3: Program:-To change the font size, colour, name and style by different controls
and its properties.
Controls:
Text box for string entry, ListBox for font name, combo boxes for size and style, radio
buttons for colors.
Font names are assigned to list box by Items property. Similarly size and styles are assigned
to the combo boxes by using Items property.
In windows application first we must design the form then for writing the code for the form,
just double click on the form anywhere. Class and methods appears automatically by just
click on the control, so remember don’t type any function “like private void
button1_Click(object sender, EventArgs e){ }“ it comes automatically, just double click on the
button.
using System.Windows.Forms;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
109
{
InitializeComponent();
}
}
private void btncancel_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
110
After completing a program, we must think to start a new program, for that we need to just
add another window form from project menu (project ->Add Windows Form). And to run that
form we need to change the start up object from project menu (Project -> windowapp1
Properties).
10.1.4: MDI Parent Form: Multiple documents Interface (MDI) is another type of form which
can be added in our project like another form. An MDIForm is a form which consists of menus
and toolbar and used to integrate another forms of project. Generally we use MDIForm in our
project as a main page/home page.
We can create our own MDI Parent form by just changing the value of a property
(“IsMDIContainer=True”) and by using menuStrip and toolStrip controls we can create
menu and tool bar on the form.
Example-
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
111
using System.Windows.Forms;
namespace calculator
{
public partial class Form1 : Form
{
double val;
public char prevop;
public Form1()
{
InitializeComponent();
}
private void display(String snum)
{
if (prevop == '=')
{
prevop=' ';
txtdisp.Text = " ";
}
if (txtdisp.Text == " ")
txtdisp.Text = snum;
else
txtdisp.Text = txtdisp.Text + snum;
}
private void Form1_Load(object sender, EventArgs e)
{
val = 0.0;
prevop=' ';
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
112
}
private void btn1_Click(object sender, EventArgs e)
{
display(btn1.Text);
display(btn2.Text);
}
private void btn3_Click(object sender, EventArgs e)
{
display(btn3.Text);
}
private void btn4_Click(object sender, EventArgs e)
{
display(btn4.Text);
}
private void btn5_Click(object sender, EventArgs e)
{
display(btn5.Text);
}
private void btn6_Click(object sender, EventArgs e)
{
display(btn6.Text);
}
private void btn7_Click(object sender, EventArgs e)
{
display(btn7.Text);
}
private void btn8_Click(object sender, EventArgs e)
{
display(btn8.Text);
}
private void btn9_Click(object sender, EventArgs e)
{
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
113
display(btn9.Text);
}
private void btn0_Click(object sender, EventArgs e)
{
display(btn0.Text);
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
114
if (prevop == '=')
{
prevop = ' ';
txtdisp.Text = " ";
}
if (!txtdisp.Text.Contains("."))
{
if (txtdisp.Text != " ")
txtdisp.Text = txtdisp.Text + ".";
else
txtdisp.Text = "0.";
}
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
115
}
}
using System;
using System.Windows.Forms;
namespace mywindowapplication
{
public partial class currenttime : Form
{
public currenttime()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
label1.Text = DateTime.Now.ToLongTimeString();
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
}
private void button2_Click(object sender, EventArgs e)
{
timer1.Enabled = false;
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
116
}
}
Step3: Select Language for the page and ASP.NET Web Application, click on OK button.
Step4: We get the inbuilt web pages with master page; we can start designing web page
from here.
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
117
After designing the page we can run the site by just clicking on start debug or F5 button.
ASP.NET is a server side web designing platform which runs on the IIS web server of
windows operating system; we need not to install any other web server. As we know to run
any other server side scripting languages like JSP/PHP requires installing Apache or glass
fish web server.
When we drag and drop the controls on the page, automatically the html code for the design
appears in the source, where we can modify the code to change the design.
Once we have designed a home page we need to have many other web pages having the
same style of the home page, ASP.NET provides the facility to add as many web pages in
the web site using the option “Web form using Master Page” from Project menu -
>AddNewItem option.
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
118
A master page is an inbuilt home page of the ASP.NET web application, which consists of
inbuilt menus, design and login option for the page. A Master page is used in a web site as a
home page which integrates all other pages with it under the manus or link. The best thing
about a master page is that, it shares the style with all other content pages which are taken in
the site by using master page, and allows us to design uniform pages with the same style and
look. It open bydefault, in .NET 2010 with the start of the web application; it can be added as
well from the project menu.
The Page which is added to the web site using Master page is called content page, a content
page contains the master page style, menu and complete look and provide the space to
design some different contents for the different page.
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
119
After designing the page if we want to see the page working at the run time, we need to write
the action code for the particular control in C# like a windows application. In this example we
can write the code for order and cancel button.
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
120
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
namespace WebApplication1
{
public partial class WebForm2 : System.Web.UI.Page
{
SqlConnection con;
SqlCommand cmd;
protected void Page_Load(object sender, EventArgs e)
{
con = new SqlConnection("Data Source=system\\SQLExpress;Initial
Catalog=mydb;Integrated Security=SSPI");
con.open( );
}
protected void Button1_Click(object sender, EventArgs e)
{
cmd = new SqlCommand("insert into Items values('" + textBox1.Text + "','" +
textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "')", con);
cmd.ExecuteNonQuery();
Label1.Text = "Your order is placed ! Thanks";
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
121
{
Environment.Exit(0);
}
}
}
10.2.6: Runing the Web Site by just clicking on start debug button or F5 function key.
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
122
ADO.NET is the data access technology of the .NET Framework. ADO.NET provides a
common coding structure for accessing data, regardless of the data source. We can connect
to our database by ADO.NET code to access our data.
ADO is short for ActiveX Data Objects, the previous version of the data access technologies,
before the .NET Framework was introduced.
For SQL Server we can use “System.Data.SqlClient” namespace which supports SQL
Server 7.0 or later versions. And as we know that SqlServer Express Edition 2008 comes
inbuilt with .NET Framework4.0 (.NET 2010). For oracle we need to use
“System.Data.OracleClient” namespace. Here we will discuss all examples with the respect
of SQL Server database.
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
123
✓ Send commands by using the connection. Send queries to retrieve and update
the data source.
✓ Close the connection. Each connection to the data source consumes resources
on the server. Always close the connection as soon as you execute your
commands.
4. Call the Open method in Con to open the database connection with the following
line:
Con.Open();
5. Call the Close method in MyConnection to close the database connection
with the following line:
Con.Close();
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
124
Here’s the entire code listing for the preceding code example:
Using System.Data.SqlClient; // namespace using
SqlConnection Con =new SqlConnection();
Con.ConnectionString = “Data Source=(local)\\sqlexpress;Initial
Catalog=DBName;IntegratedSecurity=True”;
Con.Open();
Con.Close();
Step4: Connect to server window appears with automatically filled values in the server type,
name and authentication. CMR\SQLExpress is server name where CMR is my system name.
Click on the connect button.
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
125
Step5: Write the query in the SQL Query editor and run one by one query by clicking on the
execute button or by pressing short key (Ctrl + Shift + E)
If we have written multiple query lines in the editor, at a time one query at a time must be
selected to run otherwise it runs the first query by default.
Let’s create a database MYDB with two tables Login and Employee.
We have got the database lets design and code for Login form.
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
126
}
private void button1_Click(object sender, EventArgs e)
{
con = new SqlConnection("Data Source=CMR\\SQLExpress;Initial
Catalog=MYDB;Integrated Security=true");
con.Open();
cmd = new SqlCommand("select count(*) from Login where
username='"+textBox1.Text+"' and pass='"+textBox2.Text+"'",con);
object n;
n = cmd.ExecuteScalar();
int res;
res = (int)n;
if (res > 0) {
MessageBox.Show("valid user");
}
else {
MessageBox.Show("invalid user");
}
}
}
}
11.5: SQLCommnd and its functions: We have different types of sql queries, some query
returns rows form the table, some returns the number like count and some queries does’t
retrun any thing. All these queries cann’t be executed by any one function. To execute all
these queries SQLCommnd is having different functions.
For examples:
1. Select * from tablename; returns rows which can be executed by
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
127
ExecuteReader( ) function.
2. Select count(*) from tablename; returns number which can be executed by
ExecuteScalar( ) function.
Above ExecuteScalar( ) function is used to execute the query which returns the count. Lets
use other functions in different examples.
using System;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace myproject
{
public partial class Form1 : Form
{
SqlConnection con;
SqlCommand cmd;
public Form1()
{
InitializeComponent();
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
128
}
//Exit button
private void button3_Click(object sender, EventArgs e)
{
con.Close();
Environment.Exit(0);
}
//Clear button
private void button2_Click(object sender, EventArgs e)
{
Textbox1.text=””;
Textbox2.text=””;
Textbox3.text=””;
Textbox4.text=””;
}
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
129
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
130
if (dr.Read())
{
textBox2.Text = dr.GetValue(0).ToString();
textBox3.Text = dr.GetString(1);
textBox4.Text = dr.GetValue(2).ToString();
textBox5.Text = dr.GetString(3);
}
else
MessageBox.Show("Record not found");
}
private void deletebtn_Click(object sender, EventArgs e)
{
cmd1 = new SqlCommand("delete from emp where ino='" + textBox1.Text + "' ");
cmd1.EndExecuteNonQuery();
MessageBox.Show("Record Deleted");
}
}
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
131
Chapter #12:
Sample Project (A Human Resource Management System)
12.1: Introduction to the Project
“Human Resource Management System” is a system to manage the information about the
human resources, trainee, department and projects in a software development company,
where many people may be deployed on various running projects. Different departments
detail with head and employees. Projects detail status with employee deployed on the project
are maintained. Administrator can use this system for maintaining all these detail, and can
also manage the salary and appraisal of employees as well as changing the password for the
system security.
This project is just a test project to implement a human resource management system for a
company to help the manager to manage all information related to human resources. As we
know manually it’s difficult to manage and retrieve information in quick time, this system is an
effort to solve this problem.
❖ Employee Master
❖ Department Master
❖ Project
❖ Work_On
❖ Training
❖ Administrator
Employee Master Deals with the employee detail and functions on data like addition,
updating, deletion search and display.
Department Master module deals with the department detail and operations on the
department like adding department, search, edit and display.
Project Module maintains the status of the projects, Human resources on the projects, and
adding, editing a project.
Training module is to deals with the detail of the trainees in the company.
Administrator module is to do the appraisal of the HR and to change user and password.
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
132
use hrm;
create table login(username varchar(12),pass varchar(12));
create table project(pid int primary key,ptitle varchar(15),sdate date,tdate date,budget int);
create table workon1(eid int references employee(eid) on delete cascade,pid int references
project(pid) on delete cascade);
Login Form
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
133
using System;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace HRM
{
public partial class loginfrm : Form
{
SqlConnection con;
SqlCommand cmd;
SqlDataReader dr;
public loginfrm()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
cmd = new SqlCommand("select * from login where username='"+textBox1.Text+"'
AND pass='"+textBox2.Text+"'",con);
dr = cmd.ExecuteReader();
if (dr.Read())
{
Home_mdi hm = new Home_mdi();
this.Hide();
hm.Show();
}
else
{
MessageBox.Show("Invalid User/Password");
textBox1.Text = "";
textBox2.Text = "";
dr.Close();
}
}
private void loginfrm_Load(object sender, EventArgs e)
{
con = new SqlConnection("data source=cmr\\sqlexpress;initial
catalog=HRM;integrated security=true;");
con.Open();
}
private void button2_Click(object sender, EventArgs e)
{
con.Close();
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
134
this.Dispose();
}
}
}
12.4: MDIParent Form
Dept_Master Menu -> It doesn’t contain any options but directly connected to the
dept_form.
Project Menu -> options are New_Project, HR_on_Project, Project_status and finished
project.
Work_On Menu -> options in this menu are Emp_Deployement and Emp_Status.
Admin Menu -> It has two options for Emp_Appraisal and for changing password.
If we click on any option on the MDIParent form the related form opens inside the MDI form,
Closing child doesn’t affect the MDIParent form. That’s the reason we must have a parent
form to hold and integrate other child forms.
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
135
MDIParent Code: It has the code to integrate other forms from menus and the options.
using System.Windows.Forms;
namespace HRM
{
public partial class Home_mdi : Form
{
private int childFormNumber = 0;
public Home_mdi()
{
InitializeComponent();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Environment.Exit(0); //To exit the application
}
private void empCentreToolStripMenuItem_Click(object sender, EventArgs e)
{
Empfrm ef = new Empfrm(); //To open the Employee form
ef.Show();
}
private void empShowToolStripMenuItem_Click(object sender, EventArgs e)
{
EmpViewfrm ev = new EmpViewfrm();
ev.Show();
}
private void newProjectToolStripMenuItem_Click(object sender, EventArgs e)
{
NewProj np = new NewProj();
np.Show();
}
private void projectRequirementToolStripMenuItem_Click(object sender, EventArgs e)
{
HRonProj hr = new HRonProj();
hr.Show();
}
private void projectStatusToolStripMenuItem_Click(object sender, EventArgs e)
{
ProjStatusfrm ps = new ProjStatusfrm();
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
136
ps.Show();
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
137
inf.Show();
}
}
}
using System.Windows.Forms;
using System.Data.SqlClient;
namespace HRM
{
public partial class Empfrm : Form
{
SqlConnection con;
SqlCommand cmd;
SqlDataReader dr;
public Empfrm()
{
InitializeComponent();
}
private void Empfrm_Load(object sender, EventArgs e)
{
con = new SqlConnection("data source=cmr\\sqlexpress;initial
catalog=HRM;integrated security=true;");
con.Open();
button2.Text = "AddNew";
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
138
if (dr.Read())
{
textBox2.Text = dr.GetValue(1).ToString();
textBox3.Text = dr.GetValue(2).ToString();
dateTimePicker1.Text = dr.GetValue(3).ToString();
textBox4.Text = dr.GetValue(4).ToString();
textBox5.Text = dr.GetValue(5).ToString();
textBox6.Text = dr.GetValue(6).ToString();
}
else
MessageBox.Show("ID Not Found");
dr.Close();
}
private void button2_Click(object sender, EventArgs e)
{
if (button2.Text == "AddNew")
{
cmd = new SqlCommand("select max(eid) from employee", con);
dr = cmd.ExecuteReader();
dr.Read();
int id = int.Parse(dr.GetValue(0).ToString());
id++;
button2.Text = "Save";
dr.Close();
Clear();
textBox1.Text =id.ToString();
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
139
Clear();
}
}
private void button3_Click(object sender, EventArgs e)
{
string qry = "update employee set
name='"+textBox2.Text+"',designation='"+textBox3.Text+"',doj='"+dateTimePicker1.Value+"',
dept='"+textBox4.Text+"',spl='"+textBox5.Text+"',salary='"+textBox6.Text+"' where
eid="+textBox1.Text+" ";
cmd = new SqlCommand(qry,con);
cmd.ExecuteNonQuery();
MessageBox.Show("Record Updated");
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
140
}
}
using System.Windows.Forms;
using System.Data.SqlClient;
namespace HRM
{
public partial class EmpViewfrm : Form
{
SqlConnection con;
SqlCommand cmd;
SqlDataReader dr;
SqlDataAdapter da = null;
SqlCommandBuilder cb = null;
DataTable dt = null;
BindingSource bs = null;
public EmpViewfrm()
{
InitializeComponent();
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
141
dt = new DataTable();
da.Fill(dt);
bs = new BindingSource();
bs.DataSource = dt;
dataGridView1.DataSource = bs;
}
}
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
142
using System.Windows.Forms;
using System.Data.SqlClient;
namespace HRM
{
public partial class Deptfrm : Form
{
SqlConnection con;
SqlCommand cmd;
SqlDataReader dr;
//Objects for connecting datagridview
SqlDataAdapter da = null;
SqlCommandBuilder cb = null;
DataTable dt = null;
BindingSource bs = null;
public Deptfrm()
{
InitializeComponent();
}
//search button
private void button4_Click(object sender, EventArgs e)
{
cmd = new SqlCommand("Select * from dept where dname='" + textBox1.Text + "'",
con);
dr = cmd.ExecuteReader();
if (dr.Read())
{
textBox2.Text = dr.GetValue(1).ToString();
textBox3.Text = dr.GetValue(2).ToString();
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
143
}
else
MessageBox.Show("Dept Name Not Found");
dr.Close();
}
//Addnew/Save Button
private void button1_Click(object sender, EventArgs e)
{
if (button1.Text == "Add_New_Dept")
{
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox1.Focus();
button1.Text = "Save";
}
}
}
//Update button
private void button2_Click(object sender, EventArgs e)
{
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
144
else
{
cmd = new SqlCommand("delete from dept where dname='" + textBox1.Text + "'
", con);
cmd.ExecuteNonQuery();
MessageBox.Show("Record Deleted");
Clear();
}
}
}
dt = new DataTable();
da.Fill(dt);
bs = new BindingSource();
bs.DataSource = dt;
dataGridView1.DataSource = bs;
}
public void Clear()
{
textBox1.Text = "";
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
145
textBox2.Text = "";
textBox3.Text = "";
}
}
}
using System.Windows.Forms;
using System.Data.SqlClient;
namespace HRM
{
public partial class NewProj : Form
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
146
{
SqlConnection con;
SqlCommand cmd;
SqlDataReader dr;
public NewProj()
{
InitializeComponent();
}
private void NewProj_Load(object sender, EventArgs e)
{
con = new SqlConnection("data source=cmr\\sqlexpress;initial
catalog=HRM;integrated security=true;");
con.Open();
}
}
else
MessageBox.Show("Project Id Not Found");
dr.Close();
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
147
int id = int.Parse(dr.GetValue(0).ToString());
id++;
button2.Text = "Save";
dr.Close();
Clear();
textBox1.Text = id.ToString();
}
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
148
MessageBox.Show("Record Deleted");
Clear();
}
}
}
public void Clear()
{
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox7.Text = "";
textBox6.Text = "";
dateTimePicker1.Text = "1 / 1 / 2000";
dateTimePicker2.Text = "1 / 1 / 2000";
}
}
}
12.9: HR_On_Project Form:
using System.Windows.Forms;
using System.Data.SqlClient;
namespace HRM
{
public partial class HRonProj : Form
{
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
149
SqlConnection con;
SqlCommand cmd;
SqlDataReader dr;
SqlDataAdapter da = null;
SqlCommandBuilder cb = null;
DataTable dt = null;
BindingSource bs = null;
public HRonProj()
{
InitializeComponent();
}
dt = new DataTable();
da.Fill(dt);
bs = new BindingSource();
bs.DataSource = dt;
dataGridView1.DataSource = bs;
}
}
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
150
using System.Windows.Forms;
using System.Data.SqlClient;
namespace HRM
{
public partial class ProjStatusfrm : Form
{
SqlConnection con;
SqlDataAdapter da = null;
SqlCommandBuilder cb = null;
DataTable dt = null;
BindingSource bs = null;
public ProjStatusfrm()
{
InitializeComponent();
}
private void ProjStatusfrm_Load(object sender, EventArgs e)
{
con = new SqlConnection("data source=cmr\\sqlexpress;initial
catalog=HRM;integrated security=true;");
con.Open();
da = new SqlDataAdapter("select * from project1", con);
cb = new SqlCommandBuilder(da);
dt = new DataTable();
da.Fill(dt);
bs = new BindingSource();
bs.DataSource = dt;
dataGridView1.DataSource = bs;
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
151
}
}
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
152
using System.Windows.Forms;
using System.Data.SqlClient;
namespace HRM
{
public partial class EmpDepfrm : Form
{
SqlConnection con;
SqlCommand cmd;
SqlDataReader dr;
SqlDataAdapter da = null;
SqlCommandBuilder cb = null;
DataTable dt = null;
BindingSource bs = null;
public EmpDepfrm()
{
InitializeComponent();
}
private void EmpDepfrm_Load(object sender, EventArgs e)
{
con = new SqlConnection("data source=cmr\\sqlexpress;initial
catalog=HRM;integrated security=true;");
con.Open();
}
private void button1_Click(object sender, EventArgs e)
{
da = new SqlDataAdapter("select * from employee where dept='" + comboBox1.Text +
"' AND spl='" + comboBox2.Text + "' ", con);
cb = new SqlCommandBuilder(da);
dt = new DataTable();
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
153
da.Fill(dt);
bs = new BindingSource();
bs.DataSource = dt;
dataGridView1.DataSource = bs;
}
private void button2_Click(object sender, EventArgs e)
{
cmd = new SqlCommand("insert into workon1
values("+textBox1.Text+","+comboBox3.Text+")",con);
cmd.ExecuteNonQuery();
MessageBox.Show("Done");
da = new SqlDataAdapter("select * from workon1", con);
cb = new SqlCommandBuilder(da);
dt = new DataTable();
da.Fill(dt);
bs = new BindingSource();
bs.DataSource = dt;
dataGridView2.DataSource = bs;
}
}
}
12.13: Employee status form design and code is similar to Employee View form except
it selects information from multiple tables:
using System.Windows.Forms;
using System.Data.SqlClient;
namespace HRM
{
public partial class Emp_statusfrm : Form
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
154
{
SqlConnection con;
SqlDataAdapter da = null;
SqlCommandBuilder cb = null;
DataTable dt = null;
BindingSource bs = null;
public Emp_statusfrm()
{
InitializeComponent();
}
private void Emp_statusfrm_Load(object sender, EventArgs e)
{
con = new SqlConnection("data source=cmr\\sqlexpress;initial
catalog=HRM;integrated security=true;");
con.Open();
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
155
using System.Windows.Forms;
using System.Data.SqlClient;
namespace HRM
{
public partial class Traineefrm : Form
{
SqlConnection con;
SqlCommand cmd;
SqlDataReader dr;
public Traineefrm()
{
InitializeComponent();
}
}
dr.Close();
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
156
dr.Close();
}
private void button1_Click(object sender, EventArgs e)
{
if (button1.Text == "AddNew")
{
cmd = new SqlCommand("select max(tid) from trainee", con);
dr = cmd.ExecuteReader();
dr.Read();
int id = int.Parse(dr.GetValue(0).ToString());
id++;
button1.Text = "Save";
dr.Close();
Clear();
textBox1.Text = id.ToString();
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
157
}
}
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
158
using System.Windows.Forms;
using System.Data.SqlClient;
namespace HRM
{
public partial class Trainedfrm : Form
{
SqlConnection con;
SqlDataAdapter da = null;
SqlCommandBuilder cb = null;
DataTable dt = null;
BindingSource bs = null;
public Trainedfrm()
{
InitializeComponent();
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
159
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker2.CustomFormat = "dd/MM/yyyy";
dateTimePicker2.Format = DateTimePickerFormat.Custom;
}
//Trainee between the dates
private void button1_Click(object sender, EventArgs e)
{
label3.Text = "Trainee List between the Above Dates";
da = new SqlDataAdapter("select * from trainee where doj between '" +
dateTimePicker1.Value + "' AND '" + dateTimePicker2.Value + "' ", con);
cb = new SqlCommandBuilder(da);
dt = new DataTable();
da.Fill(dt);
bs = new BindingSource();
bs.DataSource = dt;
dataGridView1.DataSource = bs;
}
//All Trainee
private void button2_Click(object sender, EventArgs e)
{
label3.Text = "All Trainee Details";
da = new SqlDataAdapter("select * from trainee", con);
cb = new SqlCommandBuilder(da);
dt = new DataTable();
da.Fill(dt);
bs = new BindingSource();
bs.DataSource = dt;
dataGridView1.DataSource = bs;
}
}
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
160
using System.Windows.Forms;
using System.Data.SqlClient;
namespace HRM
{
public partial class EmpAppfrm : Form
{
SqlConnection con;
SqlCommand cmd;
SqlDataReader dr;
public EmpAppfrm()
{
InitializeComponent();
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
161
dr.Close();
}
//Code increase salary of a dept.
private void button1_Click(object sender, EventArgs e)
{
cmd = new SqlCommand("update employee set salary=salary+'"+textBox1.Text+"'
where dept='"+comboBox1.Text+"' ",con);
cmd.ExecuteNonQuery();
MessageBox.Show(textBox1.Text +" Increament is done for the dept
"+comboBox1.Text);
}
//To increase salary for one employee
private void button2_Click(object sender, EventArgs e)
{
cmd = new SqlCommand("update employee set salary=salary+'"+textBox2.Text+"'
where eid=" +textBox3.Text + " ", con);
int r= cmd.ExecuteNonQuery();
if (r == 1)
MessageBox.Show(textBox2.Text+" Increament is done for the Employee: " +
textBox3.Text);
else
MessageBox.Show("Invalid Employee ID");
}
private void textBox3_Leave(object sender, EventArgs e)
{
cmd = new SqlCommand("select name from employee where eid="+textBox3.Text+"
", con);
dr = cmd.ExecuteReader();
dr.Read();
textBox4.Text = dr.GetString(0);
dr.Close();
}
}
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
162
using System.Windows.Forms;
using System.Data.SqlClient;
namespace HRM
{
public partial class changePassfrm : Form
{
SqlConnection con;
SqlCommand cmd;
SqlDataReader dr;
public changePassfrm()
{
InitializeComponent();
}
private void changePassfrm_Load(object sender, EventArgs e)
{
con = new SqlConnection("data source=cmr\\sqlexpress;initial
catalog=HRM;integrated security=true;");
con.Open();
}
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
163
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
164
Bibliography
Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication