0% found this document useful (0 votes)
108 views109 pages

C#

This document discusses variables, data types, operators, and strings in C#. It defines variables as memory locations that can store values that vary. It lists common data types like integers, floats, decimals, characters, and strings. It describes different operators like arithmetic, relational, logical, assignment, increment/decrement, ternary, and bitwise. It provides examples of using strings, built-in string functions, converting case, and checking if a string starts or ends with something.

Uploaded by

Ruchitha Ngowda
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
108 views109 pages

C#

This document discusses variables, data types, operators, and strings in C#. It defines variables as memory locations that can store values that vary. It lists common data types like integers, floats, decimals, characters, and strings. It describes different operators like arithmetic, relational, logical, assignment, increment/decrement, ternary, and bitwise. It provides examples of using strings, built-in string functions, converting case, and checking if a string starts or ends with something.

Uploaded by

Ruchitha Ngowda
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 109

C# ( c sharp)

Variable:
It is a memory location which is used to store or hold the value.the
value which is entred is not fixed it varies.

Datatype:
It is used to represent what type of data that the user is going to
enter.
They are

Byte byte byte an integer from 0 to 255.


Int16 short short an integer from –32,768 to 32,767.
Int32 integer int an integer from –2,147,483,648 to
2,147,483,647.
Int64 long long an integer from about –9.2e18 to 9.2e18.
Single single float a single-precision floating point number from
Approximately –3.4e38 to 3.4e38.
Double double double a double-precision floating point number
from
Approximately –1.8e308 to 1.8e308.
Decimal decimal decimal a 128-bit fixed-point fractional number
that
Supports up to 28 significant digits.
Char char char a single 16-bit unicode character.
String string string a variable-length series of unicode
characters.
Boolean boolean bool a true or false value.
Datetime date *

Operators:
An operator is one which operates on operands or variables.
They are
 Arithmetic operator
 Relational operator
 Logical operator
 Assignment operator
 Increment and decrement operator
 Ternary or conditional operator
 Bitwise
 Comma

Arithmetic: used to perform arithmetic operations.


+,-,*,/,%
Relational operator or comparison operator:
> ,<, >= ,<= ,!= ,==
It produces boolean values . That is true or false.

Logical operator:
&& (logical and)
|| (logical or)
! (logical not)

True && true = true


True && false =false
False && true=false
False && false= false
Note: both the conditions must be true to obtain final value true.

|| (logical or)
Any one of the condition must be true to obtain final value true.

True || true = true


True || false = true
False || true = true
False || false = false

! (logical not)
It produces opposite result.

! ( true ) = false
! ( false ) = true

Assignment operator:
It uses the symbol "=" . Used to assign right hand side (rhs ) value to
left hand side (lhs ).
Ex: a =10

Increment and decrement operator:


Incrementing the value by one (it uses ++)
Decrementing the value by one (it uses --)
Pre increment and post increment
Pre decrement and post decrement

Pre increment:
A=10
B=++a
A=11
B=11
Post increment:
A=10
B=a++
B=10
A=11

Simillarly pre and post decrement.


Ternary or conditional operator:
Ternary means three. It contains 3 expressions.
Condition, value1,value2
(condition)?value1:value2

If the condition is true , then value 1 is taken.


If the condition is false then value2 is taken.

C= (a>b)?a:b;

Bitwise operator:
It operates on binary digits.
They are
& , | , ^ , << , >>

Comma operator:
Int a,b;

To display a message :

Microsoft visual studio


File --new---project-----select ( visual c#) and console application
Enter the name ex: program1 (in the required folder)and ok.

Console-------------> it is a class.
Writeline------------> method

To run the program


Press control + f5 funciton key.
<---------------------------------------------------------------------->
Note:

The keyboard values are entered after the execution. It is in the


form of string.

Int x = int.parse(console.readline());
double y = double.parse(console.readline());

console.writeline(x);
console.writeline(y);
<---------------------------------------------------------------------------------------------
----------------------------------->
Reading from the keyboard
Console.write("enter name : ");

//to accept for the console

string name = console.readline(); //reads as a string from the


keyboard

console.clear(); // clears the screen

console.writeline("name : " + name);


<---------------------------------------------------------------------------------------------
------------------------------------------------------->
//to add two numbers
console.write("a = ");
int a = int.parse(console.readline());

console.write("b = ");
int b = int.parse(console.readline());
//to read other data types
//double d = double.parse(console.readline());
//long l = long.parse(console.readline());
//float f = float.parse(console.readline());

int c = a + b;

//console.writeline("sum of "+a+"+"+b+"="+
c);

//to change console fore and back color

console.foregroundcolor = consolecolor.white;
console.backgroundcolor = consolecolor.red;

console.writeline("sum of {0} + {1} = {2}",a,b,c);


<---------------------------------------------------------------------------------------------
-------------------------------------------------->

Console.write("a = ");
int a = int.parse(console.readline());

console.write("b = ");
int b = int.parse(console.readline());

//to read other data types


//double d = double.parse(console.readline());
//long l = long.parse(console.readline());
//float f = float.parse(console.readline());

if (a > b)
console.writeline(" a is big " + a);
else
console.writeline(" b is big" + b);

<---------------------------------------------------------------------------------------------
------------------------------------------------------>

//control statements in c#
// to find the largest of 3 numbers
console.write("enter number1 : ");
int a = int.parse(console.readline());
console.write("enter number2 : ");
int b = int.parse(console.readline());
console.write("enter number3 : ");
int c = int.parse(console.readline());
int i = 10;

if (a > b && a > c) // boolean expression true/flase


{
console.writeline("{0} is the largest
number", a);
}
else if ( b > c)
{
console.writeline("{0} is the largest number",
b);
}
else
{
console.writeline("{0} is the largest number",
c);
}
<------------------------------------------------------------------------------------>
Switch case :
Switch(expression)
{
Case label:
Statement;
Break;
Case label:
Statement;
Break;
Case label:
Statement;
Break;
Default:
Statement;
Break;
}

console.write("input number : ");


int number = int.parse(console.readline());
switch (number)
{
case 1:
console.writeline("you entered number
: {0}", number);
break;
case 2:
console.writeline("you entered number
: {0}", number);
break;
case 3:
console.writeline("you entered number
: {0}", number);
break;
default:
console.writeline("you entered number
> 3");
break;

}
<----------------------------------------------------------------------------------------->

console.write("input string : ");


string choice = console.readline();
switch (choice)
{
case "one":
console.writeline("you entered number
: {0}",choice);
break;
case "two":
console.writeline("you entered number
: {0}", choice);
break;
case "three":
console.writeline("you entered number
: {0}", choice);
break;

default:
console.writeline("choice not found");
break;
}
<------------------------------------------------------------------------->

Strings:
Built in functions:
The followings are the functions of string class.
Startswith()
Endswith()
Equals()
Length()
Replace()

Toupper: this functio is used to convert the string into uppercase.


Tolower : this function is used to convert the string into lowercase.

//declaration
string s = "welcome to strings in c#";
console.writeline("length : {0}", s.length);

string uppercase = s.toupper();

string lowercase = s.tolower();


console.writeline("message : {0}", s);
console.writeline("uppercase : {0}", uppercase);
console.writeline("lowercase : {0}", lowercase);

<----------------------------------------------------------------------------------------->
Startswith() : this function is used to check string that starts with.

String url = "http://www.yahoo.com";

if (url.startswith("http"))
{
console.writeline("its a http request");
}
if (url.endswith(".com"))
{
console.writeline("its a commercial website");
}

<--------------------------------------------------------------------------------------->
Equals() : this function is used to compare the two strings.

String s1 = "smith";
string s2 = "smith";

if (s1 == s2)
//if(s1.equals(s2))
// if (s1.equals("amith"))
{
console.writeline("s1 == s2");
}
else
{
console.writeline("s1 != s2");
}
<-------------------------------------------------------------------------------------->
Replace () : this function is used to replace the word.

Replace function:

String message = "google is fast, google is best, google uses ajax";

console.write("enter word to search : ");


string searchword = console.readline();
console.write("enter word to replace : ");
string replaceword = console.readline();
console.writeline("message : {0}", message);
//replace the word
message = message.replace(searchword,
replaceword);
console.writeline("message after replacing : {0}",
message);
<----------------------------------------------------------------------------------------->

Iterative or repetative loop:

For loop
For(initialization;condition;updation)

Console.writeline("enter the value from the keyboard");


int n = int.parse(console.readline());
int sum, i;
sum = 0;
for (i = 1; i <= n; i++)
sum = sum + i;
console.writeline("total sum is " + sum);
1+2+3+4+5

<------------------------------------------------------------------------------->

While loop
Console.writeline("enter the value from the keyboard");
int n = int.parse(console.readline());
int i = 2;
while (i <= n)
{
console.write(i + " ");
i += 2; // i = i+2;
}

2 4 6 8 10

I = i +2------------------------------> i+=2
I = i *2------------------------------>i *=2
i=i / 2--------------------------------> i /= 2
I = i+1---------------------------->i++
I = i -1 --------------------------> i--
<---------------------------------------------------------------------------------------------
->

Do while loop
Console.writeline("enter the value from the keyboard");
int n = int.parse(console.readline());
int i = 1;
do
{
console.write(i + " ");
n = n - 1;
i = i + 1;
} while (n != 0);
<------------------------------------------------------------------------------------>
Types of programming types:
 Un structrued
 Structured
 Procedural
 Modular
 Object oriented programming language

Class and object:


Object oriented programming structure (oops):
Class and object:
Class is an user defined data type, which contains data members and
functions.

Class sample
{
Int x;---------------------------->data member or property
Void getdata();----------->function or behaviour
}

Class is a logical abstraction


Object is a physical existance

Ex:

Fruit----->class
mango, banana, orange etc-=---> objects

Class animal
{
Eye,mouth;--------data members
See() function
Eat()
}
Tiger,cat, dog----->objects

Class exam
{
What is c++
What is java
}
St1,st2,st3,st4--------->objects

Class bank
{
Deposit()
Withdrawal()
Balance()
}
Cust1,cust2,cust3-------->objects

Class is a template or blueprint or general represenation or common


representation or skeleton of application

Object:
It is an entity which shares or draws the common properties of the
class and can have its own behaviour.

Note:
Class is a logical abstraction
Object is a physical in existance.

Prime concepts of oops:


 Data hiding
 Abstraction
 Encapsulation
 Inheritance
 Polymorphism

Data hiding:
In procedural oriented programming language "c", there is no security
for the data. The data could be accessed in any function and could be
modified.
Data flows freely around the program.
In order to provide exclusively security for the data and not for the
functions, the prime concept of oops , data hiding came in.
Here data is treated as an important element or critical element.
Abstraction of data:
The data member of the class should be used with in the member
functions of the class.
The data is abstracted.
Encapsulation:
A class can contain any number of data members and functions.
The grouping up of data members and functions together is
encapsulation.
It is used to separte the essential entities from non essential.
Data members and functions are encapsulated to form a family called
"class"
Inheritance:
It is the process of creating new class by making use of existing class.
It provides a concept called "reusability". Rather than writting the
code again and again reuse the existing properties.
It avoids wastage of system time, user time and system memory.
Polymorphism:
Poly means many and morphism means forms. An object can take
many or multiple forms.

Syntax:
Class classname
{
Datamembers
Functions or methods
}
Ex:
Class sample
{
Int x;------------>data member
Void get()-------->function or method
{
}
}

Object = data + method

Syntax:
Class classname
{

}
Ex:
Class test
{

}
Creation of object:
Test t=new test();

Access specifier:
It is used to specify the accessibility of the members of the class.
They are
Private,public,protected and internal

Note:
By default the data members of the class are private.
Class test
{
Public int x;
}
Class test1
{
Static void main(string [] args)
{
Test t=new test(); // t is an object of class test
T.x=100;
Console.writeline(t.x);
}
}
<-------------------------------------------------------->
Class test
{
int x;
public void get() // functions
{
x = 250;
}
public void put() // functions
{
console.writeline(x);
}

}
class test1
{
static void main(string[] args)
{
test t = new test();
t.get();
t.put();

}
}
<----------------------------------------------------------->
Class demo
{
int x, y;
public void getdata(int m,int n)
{
x = m;
y = n;
}
public void putdata()
{
console.writeline(x);
console.writeline(y);
}

}
class demo1
{
static void main(string[] args)
{
demo d1 = new demo();
demo d2 = new demo();

int a = int.parse(console.readline());
int b = int.parse(console.readline());
int c = int.parse(console.readline());
int d = int.parse(console.readline());
d1.getdata(a,b );
d2.getdata(c,d );
d1.putdata();
d2.putdata();

}
}
<-------------------------------------------------------->
Class demo
{
int x, y;
public void getdata(int x,int y)
{
this. X =x;
this. Y =y;
}
public void putdata()
{
console.writeline(x);
console.writeline(y);
}

}
class demo1
{
static void main(string[] args)
{
demo d1 = new demo();
demo d2 = new demo();
int a = int.parse(console.readline());
int b = int.parse(console.readline());
int c = int.parse(console.readline());
int d = int.parse(console.readline());
d1.getdata(a,b );
d2.getdata(c,d );
d1.putdata();
d2.putdata();

}
}

Note:
Object communicate to the data through the function.
Function is an interface between data and the object.
<----------------------------------------------------------->
Note:
Data member irrespective of any category can be initialized.
(private,public,protected)
Private int x=100;

Constructor:

For default initialization or automatic initialization.


It is called as soon as the object or instance is created.

Constructor does not have return type. (constructor is to initialize the


members of the class and constructor is called for object. Obviously its
data type is also class type).

It has the same name as that of the class name.

Class test
{
int x;
public test() // constructor
{
x = 100;
}
public void display()
{
console.writeline(x);
}
}

class test1
{
static void main(string[] args)
{
test t = new test();
t.display();
}
}
<-------------------------------------------------------------------->
 Default constructor or parameter less constructor
 Parameterized constructor
Class test
{
int x;
public test()
{
x = 100;
console.writeline("constructor is called" + x);
}
// public void display()
//{
// console.writeline(x);
// }
}

class test1
{
static void main(string[] args)
{
new test();

}
}
<------------------------------------------------------->

Constructor overloading:

Class abc
{
int x, y;
public abc(int m) // single parameter constructor
{
x = y= m;
}
public abc(int a, int b) // multi parameter constructor
{
x = a;
y = b;
}
public void output()
{
console.writeline(x + " " + y);
}
}

class program
{
static void main(string[] args)
{
abc obj = new abc(100);
abc obj1 = new abc(2000, 300);
obj.output();
obj1.output();

}
}

Garbaze collector:
It is used to deallocate the memory.
Protected void finalize()
{
Base.finalize();
}

This : keyword used to refer to the current running object


Class temp
{
int x, y;
public temp(int x,int y) // constructor
{
this. X =x;
this. Y =y;
}
public void putdata()
{
console.writeline(x);
console.writeline(y);
}
}
class temp1
{
static void main(string[] args)
{
int a = int.parse(console.readline());
int b = int.parse(console.readline());
int c = int.parse(console.readline());
int d = int.parse(console.readline());
temp d1 = new temp(a,b );
temp d2 = new temp(c,d);

d1.putdata();
d2.putdata();

}
}
<---------------------------------------------------------->

Class sample
{
int x, y;
public void getdata()
{
x = 100;
y = 200;
}
public void display()
{
console.writeline(x + " " + y);

}
}
class p1
{
static void main(string[] args)
{
sample s=new sample();
s.getdata();
s.display();
}
}

<------------------------------------------------------->
Using constructor:
Class sample
{
int x, y;
public sample() // consructor
{
x = 100;
y = 200;
}
public void display()
{
console.writeline(x + " " + y);

}
}
class p1
{
static void main(string[] args)
{
sample s=new sample();
s.display();
}
}
}

<------------------------------------------------------>

Class test
{
int x;
public void get()
{
x = 100;
console.writeline("the value is " + x);
}
static void main(string[] args)
{
test obj = new test();
obj.get();
}
}
<-------------------------------------------------------->
Namespace example
{
Class axis // default access modifier internal
{
int x, y; // defaut private

public axis() // non parameterized constructor


{

}
public axis(int x, int y)
{
this.x = x; // this - > self reference of the class
this.y = y;
}

public void display()


{
console.writeline(" x = {0} and y = {1}",x,y);
}

public void setx(int x) // <access-modifier> <data-type>


<function-name>(<datatype> parameter1,<datatype>
parameter2,..........<data-type> parametern) { ........ }
{
this.x = x;
}

public void sety(int y)


{
this.y = y;
}
}

class program
{
static void main(string[] args)
{
// create an class object
axis a = new axis();
//to access the member function use . Operator
a.display();
//note : data members declared at class level
are initialized to their default values
// data members declared inside
function need to initialized explicitly

axis b = new axis(10,20);


b.display();

//assigning references
axis c = b;
c.setx(20);
c.sety(30);

b.display(); // 20 30
c.display(); // 20 30

}
<--------------------------------------------------------------------------------->
Class employee
{
public static string company;
string id;
string name;
double salary;

public employee(string id, string name, double salary)


{
this.id = id;
this.name = name;
this.salary = salary;
}

public void displayinformation()


{
console.writeline("company : {0}\nid : {1}\nname
: {2}\n salary : {3}", company, id, name, salary);
}

public static void setcompanyname(string cname)


{
company = cname;
}
public static string getcompanyname()
{
return company;
}
}
class program
{

static void main(string[] args)


{
//static members are accessed using the class name
if they have been declared
// as public
employee.company = "companyxyz";
employee emp1 = new employee("emp123", "smith",
23000);

emp1.displayinformation();

employee emp2 = new employee("emp456", "jordan",


30000);

emp2.displayinformation();
employee.setcompanyname("aztecsoft");
console.writeline("company name : " +
employee.getcompanyname());
}
}
}
<--------------------------------------------------------------------->
Function overloading:
Class abc
{
int x, y;
public void getdata(int m)
{
x = y = m;
}
public void getdata(int m, int n)
{
x = m;
y = n;
}
public void display()
{
console.writeline(x + "\t" + y);
}
}

class program
{
static void main(string[] args)
{
abc obj = new abc();
abc obj1 = new abc();
obj.getdata(100);
obj1.getdata(200, 300);
obj.display();
obj1.display();
}
}
Inheritance:
Syntax:
Class classname
{

}
Class classname:classname
{

}
Ex:
Class a---------------------------> base class
{

}
Class b: a------> class b is sub or derived or child class.
{

}
Note:
Under inheritance , object should be created for derived class.

Class temp // base class


{
protected int x;
public void accept(int m)
{
x = m;
}
}
class temp1: temp // temp1 is derived or child class
{
public void display()
{
console .writeline (x);
}
}
class c
{
static void main()
{
temp1 obj=new temp1();
obj.accept(1500);
obj.display();
}
}

<--------------------------------------------------------------------------------------->
Note:
The data member of the class be declared under private category.
Under inhertitance, the data member be declared under protected
category.
Member function be always under public category.

Overriding:
Intentional hiding of base class function by using derived class
function.
(provided both base and derived class contain
Same function name with same signature in tems of parameters)
Class first
{
//protected int x;
public void display()
{
console.writeline("base class method");
}
}
class second: first
{
public void display()
{
base.display();
console.writeline("sub class method");
}

class program
{
static void main(string[] args)
{
//first f = new second();
second s = new second();
s.display();

}
}
Constructor under inheritance :
Constructor fires from base class to derived class.
Class temp // base class
{
public temp() // base class cons
{
console.writeline("base class constructor");
}
}
class temp1 : temp
{
public temp1() // derived class cons
{
console.writeline("derived class constructor");
}
}
class c
{
static void main(string[] args)
{
temp1 obj = new temp1();
}
}

Class person
{
string name;
int age;
public person() { }

public person(string name, int age)


{
//console.writeline("1. Person class constructor");
this.name = name;
this.age = age;
}

public string name


{
get
{
return name;
}
}
public int age
{
get
{
return age;
}
}
}

class manager : person


{
int stocks;
public manager()
{
}

//invoking base class constrctor


public manager(string name, int age, int stocks) :
base(name,age)
{
//console.writeline("2. Manager class constructor");
this.stocks = stocks;
}

public int stocks


{
get
{
return stocks;
}
}
}
class program
{
static void main(string[] args)
{

manager m = new manager("smith", 23, 15);


console.writeline("name : " + m.name);
console.writeline("age : " + m.age);
console.writeline("stocks : " + m.stocks);

}
}
<------------------------------------------------------------------------->

Over riding :
Intentionaly hiding the base class function by using derived class.

It allows the user to write the code that the user wants.

Class windowsxp
{
public virtual void playmedifile()
{
console.writeline("palying the media file");
}
}

class windowsvista : windowsxp


{
public override void playmedifile()
{
console.writeline("palying the media file(vista)");
}
}

class program
{
static void main(string[] args)
{
// windowsvista wv1 = new windowsvista();
// wv1.playmedifile();

/*
windowsvista wv2 = new windowsxp();
wv2.playmedifile();
*/
windowsxp wxp = new windowsvista();
wxp.playmedifile();
}
}
Run time polymorphism achieved through
Virtual and override keywords
<------------------------------------------------------>
Has-a relationship or containment delegation model:

Class radio // ---------contained


{
public radio()
{
console.writeline("radio");
}

public void start()


{
console.writeline("radio started");
}

class car // ---------container class


{
public radio r;
public car()
{
r = new radio();
}
}
class program
{
static void main(string[] args)
{
car c = new car();
c.r.start();
}

Interface:

Interface is basically a kind of class. It contains abstract methods.

Ex:
Interface a
{
Void get();-----------> declared method
}

Note:
Interface members are public

Interface xyz
{
void get1();
}
class p1 : xyz
{
public void get1()
{
}

}
class program
{
static void main(string[] args)
{
p1 obj = new p1();
obj.get1();

}
}

Multiple inheritance can be implemented by using interface.

Drawing the properties from only one class and implementing any
number of interfaces.

<---------------------------------------------------------------------->
Class p1
{
public void get1()
{
console.writeline("this is class method");
}
}

interface xyz
{
void get2();
}
class p2 : p1,xyz
{
public void get2()
{
console.writeline("interface method");
}
}

class program
{
static void main(string[] args)
{
p2 obj = new p2();
obj.get1();
obj.get2();

}
}

<------------------------------------------------------------------>
Class x
{
public void get()
{
console.writeline("this is the method of class x");
}
}
class y : x
{
public void get()
{

console.writeline("this is the method of class y");


}
}

class z
{
static void main(string[] v)
{
y obj = new y();
obj.get();
}
}
<------------------------------------------------------------------->

Class x
{
public void get()
{
console.writeline("this is the method of class x");
}
}
class y : x
{
public void get()
{
base.get();
console.writeline("this is the method of class y");
}
}

class z
{
static void main(string[] v)
{
y obj = new y();
obj.get();
}
}
<------------------------------------------------------------------>

Class x
{
public void get()
{
console.writeline("this is the method of class x");
}
}
class y : x
{
public void get()
{
base.get(); // invoking base class function
console.writeline("this is the method of class y");
}
}

class z
{
static void main(string[] v)
{
y obj = new y();
obj.get();
}
}
<------------------------------------------------------------------------->
Class x
{
public void get()
{
console.writeline("this is the method of class x");
}
}
class y : x
{
public void get()
{
// base.get();
console.writeline("this is the method of class y");
}
}

class z
{
static void main(string[] v)
{
x obj = new y();
obj.get();
}
}
<---------------------------------------------------------------------------->

Class x
{
public virtual void get()
{
console.writeline("this is the method of class x");
}
}
class y : x
{
public override void get ()
{
// base.get();
console.writeline("this is the method of class y");
}
}

class z
{
static void main(string[] v)
{
x obj = new y();
obj.get();
}
}
<-------------------------------------------------------------------->
Exception handling:

Using system;

Namespace example1
{
class program
{
static void main(string[] args)
{
try
{
console.write("enter number1 : ");

int a = int.parse(console.readline());

console.write("enter number2 :");


int b = int.parse(console.readline());

int c = a / b;

console.writeline(" {0} / {1} = {2}", a, b, c);


}

catch (formatexception errorformat)


{
console.writeline("error message : " +
errorformat.message);
console.writeline("input only numbers in range 0
- 9 \nformat : number1 = 10 number2 = 20");
}

catch (overflowexception erroroverflow)


{
console.writeline("error message : " +
erroroverflow.message);
console.writeline("input integer numbers in
range {0} to {1}", int.minvalue, int.maxvalue);

catch (dividebyzeroexception errordivision)


{
console.writeline("error message : " +
errordivision.message);
console.writeline("denominator value cannot be
equal to zero");
}
catch (exception errorglobal)
{
console.writeline("error :\n : {0}",
errorglobal.tostring());
}

}
}
}
<---------------------------------------------------------------------------------------------
------------------------------------->

Finally :
Finally block executes whether the exception is thrown or not.
note:
It is used to release the resources.

Using system;
Using system.collections.generic;
Using system.text;

Namespace example4
{
class program
{
static void main(string[] args)
{
try
{
console.write("a = ");
int a = int.parse(console.readline());
console.write("b = ");
int b = int.parse(console.readline());

int c = a / b;
console.writeline(" {0} / {1} = {2}", a, b, c);

catch (dividebyzeroexception errordivision)


{
console.writeline("error message : " +
errordivision.message);
}
catch (overflowexception erroroverflow)
{
console.writeline("error message : " +
erroroverflow.message);
}
catch (formatexception errorformat)
{
console.writeline("error message : " +
errorformat.message);
}
catch (exception errorglobal)
{
console.writeline("error : \n" + errorglobal);
}

finally
{
console.writeline("executing finally block");
}
}
}
}
<-------------------------------------------------------------------------------->
Boxing and unboxing

Value types to reference type is boxing


Reference type to value type is unboxing
Using system;
Using system.collections.generic;
Using system.text;
Using system.collections ;
Namespace example1
{
class box
{
Static void main(string [] args)
{

Int i = 10; // stack


//i is a value type
float x = 15.5f;
object obj1 = x; // boxiing

//boxing
object obj = i; //heap
// unboxing
float y = (float)obj1; // unboxing

int j = (int)obj; // unboxing

console.writeline(" j = " + j);


console.writeline("y=" + y);
}
}
Auto boxing:
Data (int, float data etc) are boxed to object type automatically.

Using system.collections;
For each
arraylist numbers = new arraylist();
for (int i = 0; i < 10; i++)
numbers.add(i);
foreach (int x in numbers)
console.write(x+" ");

<------------------------------------------------------------------------->
Arraylist numbers = new arraylist();
for (int i = 0; i < 10; i++)
numbers.add(10+i);
foreach (int x in numbers)
console.write(x + " ");

Collection:

Using system.collections;
Class program
{
static void main(string[] args)
{

arraylist list = new arraylist();

///adding items one by one


list.add(1);
list.add(2);
list.add(3);

//to get the items count


int count = list.count;

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


{
console.writeline("list[{0}] = {1}", i, list[i]);
// console.writeline(list[i]);
}

//console.clear();

console.writeline("before\n");
foreach (int element in list)
{
console.writeline(element);
}

//adding collection of items


int[] items = { 40, 50, 60, 70 };
list.addrange(items);

console.writeline("\n\nafter\n");
foreach (int element in list)
{
console.writeline(element);
}

}
<------------------------------------------------------------------------------------------->

Using system;
Using system.collections.generic;
Using system.text;
Using system.collections ;

Namespace example1
{
class point
{
int x, y;

public int y
{
get { return y; }
set { y = value; }
}

public int x
{
get { return x; }
set { x = value; }
}
public point(int x, int y)
{
this.x = x;
this.y = y;
}
}

class program
{
static void main(string[] args)
{
arraylist list = new arraylist();
list.add(10);
list.add(12.3);
list.add("this is a test message");

point p = new point(10, 20);


list.add(p);
foreach (object obj in list)
{
if (obj is int)
{
int value = (int)obj;
console.writeline("{0} is integer", value);

}
else
{
if (obj is double)
{
double d = (double)obj;
console.writeline("{0} is double", d);
}
else
{
if (obj is string)
{
string message = (string)obj;
console.writeline("'{0}' is string",
message);

}
else
{
if (obj is point)
{
point pnt = obj as point;
console.writeline("\n\n x
={0} y ={1}", pnt.x, pnt.y);
}
}
}

}
}

}
}

<--------------------------------------------------------------------->

//void get(int a,int b)


//public delegate void get(int,int);

Delegate :
// declaration
public delegate void displaydelegate(string msg);

class program
{
static void main(string[] args)
{
// instantiation
displaydelegate del = new
displaydelegate(displaymessage);
//invoke a delegate
del("i was called by a delegate");
}

static void displaymessage(string msg)


{
console.writeline("message : " + msg);
}
}
<----------------------------------------------------------------------->
Public delegate void display(string msg); // declaration

class program
{
static void main(string[] args)
{
display del=new display(dis);
del("delegate was called");
}
static void dis(string msg)
{
console.writeline(msg);
}
}
<------------------------------------------------------------------->
Public delegate void display(int x); // declaration

class program
{
static void main(string[] args)
{
display a = new display(dis);
a(100);
}
static void dis(int b)
{
console.writeline(b);
}
}
<---------------------------------------------------------------------------------------->

<------------------------------------------------------------------------>
Name space:

Array declaration:

String [ ] x=new string[4]

C# also provides a foreach block that allows you to loop through the
items in a set of data.
With a foreach block, you don’t need to create an explicit counter
variable. Instead, you
Create a variable that represents the type of data for which you’re
looking. Your code will
Then loop until you’ve had a chance to process each piece of data in
the set.
The foreach block is particularly useful for traversing the data in
collections and arrays.

Delegates
Delegates allows to create a variable that “points” to a method. The
user can use this variable at any time to invoke the method. Delegates
helps to write flexible code that can be reused in many situations.
They’re also the basis for events
The first step when using a delegate is to define its signature. A
delegate variable can point only to a method that matches its specific
signature. In other words, it must have the same return type and the
same parameter types
Delegates: a delegate is a function pointer that allows to invoke a
procedure indirectly.
Delegates are the foundation for .net event handling

Namespace :
It is a package or folder or directory .it contains classes and interfaces.
To import the name space the keyword "using" is used.
Namespace myprogram
{
namespace myapp
{
public class product
{
public void put()
{
console.write("user defined name space
program");
}
}

class program1
{
static void main(string[] args)
{
product p = new product();
p.put();
}
}
}
}
<---------------------------------------------------------------------------------------------
------------------------------------------->
Partial classes
Partial classes used to split a single class into more than one source
code(.cs) file.
<---------------------------------------------------------------------------------------------
->

Generic:
Writting a single function or class for a family of similar classes or
functions in generic manner.

Function template
Class template

Using system;
Using system.collections.generic;
Using system.text;
Using system.collections ;

Namespace example1
{
class program
{
static void main(string[] args)
{
int[ ] a = { 10, 20, 30, 40, 50, 60 };
string[] names = { "ramesh", "suresh", " umersh",
"james" };

console.writeline("integer elements :\n");


//display<int>(a);
display(a);
console.writeline("\n\nnames\n");
//display<string>(names);
display(names);
}

static void display<tdatatype>(tdatatype[] array)


{
for (int i = 0; i < array.length; i++)
{
console.writeline("array[{0}] = {1}", i, array[i]);
}
}
}
}
<--------------------------------------------------------------------------->

class employee < telement>


{
telement empno;
public void getdata( telement m)
{
empno=m;
}
public void display()
{
console.writeline (empno);
}
}

class program
{
static void main(string[] args)
{
employee<int> e1 = new employee<int>();
employee<double> e2 = new employee<double>();
e1.getdata(100);
e2.getdata(80.5);
e1.display();
e2.display();
}
}
}

Namespace example2
{
class gstack<telement>
{
stack s;
public gstack()
{
s = new stack();
}

public void push(telement element)


{
s.push(element);
}

public telement pop()


{
return (telement)s.pop();
}

public telement peek()


{
return (telement)s.peek();
}
}
class program
{
static void main(string[] args)
{
gstack<int> s = new gstack<int>();
s.push(10);
s.push(20);
s.push(30);
s.push(40);

console.writeline("top element : " + s.peek());

console.writeline("removing element : " + s.pop());

console.writeline("top element : " + s.peek());

}
}
}
<---------------------------------------------------------------------------------------------
-------------------------------------------------------------------------->
Using system.collections;
Namespace example3
{
class program
{
static void main(string[] args)
{
//arraylist - list
//hashtable - dictionary
//sortedlist
//stack
//queue

list<int> list = new list<int>();

list<string> lst = new list<string>();


dictionary<int, string> d = new dictionary<int,
string>();

stack<string> names = new stack<string>();

queue<int> q = new queue<int>();

}
}
<---------------------------------------------------------------------------------------->

File handling:

Using system;
Using system.collections.generic;
Using system.text;
Using system.io;
Namespace example3
{
class program
{
static void main(string[] args)
{
string dirpath = @"c:\m\";
console.write("enter the fileto search : ");
string filename = console.readline().trim();

string searchfilepath = dirpath + filename;

if (file.exists(searchfilepath))
{
console.write("file exists delete (y/n) : ");
char ch = char.parse(console.readline());
if (ch.tostring().tolower() == "y")
{
file.delete(searchfilepath);
console.writeline("file deleted
successfully");
}
}
else
{
console.write("file doesnot exist create new file
(y/n) : ");
char ch = char.parse(console.readline());
if (ch.tostring().tolower() == "y")
{
file.create(searchfilepath);
console.writeline("file create successfully");
}
}
}
}
}
<---------------------------------------------------------------------------------------------
-->

Using system.io;
Using system.text;
Using system;

Namespace example5
{
class program
{
static void main(string[] args)
{
console.write("enter filename : ");
string filename = console.readline();

string path = @"c:\test\" + filename;

if (file.exists(path))
{
fileinfo fileinfo = new fileinfo(path);
console.writeline("filename : " +
fileinfo.name);
console.writeline("path : " + fileinfo.fullname);
console.writeline("created : " +
fileinfo.creationtime);
console.writeline("last accessed : " +
fileinfo.lastaccesstime);
console.writeline("file extension : " +
fileinfo.extension);
console.writeline("file size : " + fileinfo.length);
}
}
}
}
<------------------------------------------------------------------>
Using system;
Using system.io;

Namespace example6
{
class program
{
static void main(string[] args)
{
//listfiles(@"c:\windows");
listdirectories(@"c:\");
}

static void listfiles(string path)


{
directoryinfo dir = new directoryinfo(path);
fileinfo[] fileinfo_array = dir.getfiles();

foreach (fileinfo info in fileinfo_array)


{
console.writeline("{0}\t{1}\t{2}", info.name,
info.creationtime, info.length);
}
}

static void listdirectories(string path)


{
directoryinfo dir = new directoryinfo(path);
directoryinfo[] dirinfo_array = dir.getdirectories();

foreach (directoryinfo d in dirinfo_array)


{
console.writeline("{0}\t{1}", d.name,
d.creationtime);
}
}
}
}
<---------------------------------------------------------------------------------------------
-->
Using system;
Using system.io;

Namespace example7
{
class program
{
static void main(string[] args)
{

if (!directory.exists(@"c:\demo"))
{
directory.createdirectory(@"c:\demo");
}
//directory.delete(@"c:\demo"); //delete empty
directory
// directory.delete(@"c:\demo", true);

}
}
}
<---------------------------------------------------------------------------------------------
>

To check iis (internet information service) working or not

Then
Run----cmd----type it as follows
Http://localhost

or
To start or stop iis server:
Start---control panel---performance and
maintanance----administrative tools---- double click internet
information
Service(iis)---
Select default website

To create a virtual directory as follows:


Start---control panel---performance and
maintanance----administrative tools---- double click internet
information services---expand computer name ----expand
websites----click right mouse button on default website----
new---virtual directory---next--enter the alias name ex:
abc----enter the directory path(ex: c:/inetpub/www
root)---next---select
Write and browse-----finish

File---new -----website-----click browse


(file system)
(visual c#)------------->select ex:c:/inetpub/www root/abc
And ok

Start----programs----microsoft visual studio 2005-------microsoft visual


studio

To create a new website:

File----new---website----asp.net website----select the location and


language (file system and visual c#) and enter the website name
-----ok

Web technologies ( html, java script, asp.net, css,xml)

Asp.net (active server pages .net) is a web development technology


from microsoft. It allows users to build dynamic web sites, web
applications, xml web services etc. It is part of microsoft’s .net
platform and is the successor to microsoft’s active server pages (asp)
technology. Asp.net is built on the common language runtime,
allowing programmers to write asp.net code using vb.net and c#.
Difference between asp.net and asp
Asp.net is based on an object oriented and asp is based on a
procedural and event-driven
Event-driven programming model. Programming model applications
written in asp.net are compiled. Applications written in asp are
interpreted.
Asp.net provides a better separtion between asp.net does not
support the code-behind
Layout and logic using the code-behind feature.
Feature.
State management of control is done easily state management of
controls is very control
Using enableviewstate property of the complex and involves
extensive programming.
Control class.
Asp.net pages can only support one asp pages support multiple
programming
Programming language on a page. Languages on a page.
Asp.net files have .aspx file extension. Asp files have .asp files
extension.
Option explicit is set to on by default. Option explicit is set to off by
default.
Asp.net provides validation controls for user input validation is done
using programming
Implementing user input validation. Logic, as asp does not provides
any controls or
In-built functions to implement user input validation.

Advantages of asp.net:

asp.net drastically reduces the amount of code required to build


large applications
asp.net makes development simpler and easier to maintain with an
event-driven,
Server-side programming model.
asp.net pages are easy to write and maintain because the source
code and html are
Together
the source code is compiled initially when the page is requested.
Execution becomes fast
As the web server compiles the page the first time, when it is
requested. The server saves
The compiled version of the page to use it the next time when the
page is requested
the html produced by the asp.net page is sent back to the browser.
The application
Source code is not sent thereby providing security.
asp.net allows easy deployment. There is no need to register
components because the
Configuration information is built-in.
asp.net validates information (validation controls) entered by the
user without writing a
Single line of code.

Note:
Web server which is used to execute web applictions such as html,
java script, asp.net and xml

Iis : it is a web server

Internet information service

The procedure how asp.net works:

A web browser sends a request for an asp.net file to a web server by


using a uniform
resource locator (url).
the web server, iis, receives the request and retrieves the
appropriate asp.net file from the disk or memory.
the web server forwards the asp.net file to the asp.net script engine
for processing.
Client computer requests an asp.net
Client receives the output as html content
the asp.net script engine reads the file from top to bottom and
executes any server side scripts it encounters.
the processed asp.net file is generated as an html document, and the
asp.net engine sends the html page to the web server.
the web server then sends the html page to the client.
the web browser interprets the output and displays it in user defined
format.

Asp.net comes with the extension (.aspx)


C# comes with the extension (.cs)

Website contains design and source windows.

Design window is used to place the controls.


Source window is automatically generates html informations.

Note: when the control is added on to the design window


The appropriate html tags are given in source code automatically.

Any control contains an important property called "id"

Tool box is one which contains the control.

To get a tool box (view menu-----select tool box)

At the right side of the window , there is explorer called

"solution explorer "

This provides the buttons for view code, view designer,properties


etc

Ide : integrated development environment


Visual web or visual studio

Console application or windows application

Visual c# express edition

Coding behind the page (design web page)

Csharp

Note :

Any asp website comes with


(aspx file and cs file)

Tool box contains controls category as follows


Standard controls
Data control
Validation control
Navigation control
Login control
Web parts
Html controls
Crystal reports
General

Standard controls:
These are web server controls.

Pointer,label,textbox,button, link button,image button,hyperlink,drop


down list,list box,check box,checkbox list,radio button,radiobutton
list,image ,image map,table , bulleted list,hidden field, literal
,calendar,adrotator,file upload,multiview,panel etc

Data controls:
Gridview, datalist,details view,formview,repeater,sql data source,

Validataion control:
Required field validator,range validator,regular expression
validator,compare validator,custom validator.

Navigation control :
Sitemappath and menu

Login control:
Login view,login name,create user wizard,change password

Html controls:
Table, text area ,image
<-------------------------------------------------------------------------------------------->
Difference between html server control and web server control
Html controls are defined using html tag and are processed by the
web browser. Whereas,server controls are first processed by the
server, and then their corresponding html tags are generated. The
html tags, thus generated, are further processed by the web browser
before rendering them.

Design time property setting:


Select label from the tool box and drop it on to design window.
Set the label property as ex: country (text property)
Simillarly select text box from the tool box.
Set the property as "this is text box" (text property)

Note:
To select property window , press (f4)

Server controls:
Asp.net provides two sets of server controls:
It allows you to turn static html tags into objects—called
Server controls—that you can program on the server.
html server controls
Html server controls provide an object interface for standard html
elements. They
Provide three key features:
They generate their own interface: you set properties in code, and the
underlying html
Tag is updated automatically when the page is rendered and sent to
the client.
They retain their state: because the web is stateless, ordinary web
pages need to go to a
Lot of work to store information between requests. For example,
every time the user
Clicks a button on a page, you need to make sure every control on
that page is refreshed
So that it has the same information the user saw last time. With
asp.net, this tedious
Task is taken care of for you. That means you can write your program
the same way you
Would write a traditional windows program.
They fire events: your code can respond to these events, just like
ordinary controls in a
Windows application. In asp code, everything is grouped into one
block that executes
From start to finish. With event-based programming, you can easily
respond to individual
User actions and create more structured code. If a given event doesn’t
occur, the
Event handler code won’t be executed.

<------------------------------------------------------------------------->

To place the control to the required postion


Layout-----postion---- auto position-------css positioning -----relatively
positioned
Protected void button1_click(object sender, eventargs e)
{
//to display the text in the textbox
textbox1.text = datetime.now.tostring();
textbox1.tooltip="textbox"
}

Built in objects of asp.net :


 Session
 Application
 Request
 Response
 Server
 Trace

Protected void page_load(object sender, eventargs e)


{
response.write("using response object");

}
Protected void button1_click(object sender, eventargs e)
{
response.redirect("http://www.google.com");
}
Protected void page_load(object sender, eventargs e)
{
string a;
a = request.applicationpath;
response.write(a);
string b;
b = request.browser.browser;
response.write(b);
string c;
c = request.filepath;
response.write(c);
string d;
d = request.httpmethod;
response.write(d);
}

Protected void page_load(object sender, eventargs e)


{
response.write(server.machinename);

}
Protected void page_load(object sender, eventargs e)
{
trace.isenabled = true;
}

Select two labels, two textboxes


One button
Two more labels.
Username
Password

Set the textbox2 (password) the property is "text mode" set it as


(password)

<------------------------------------------------------------------------->
Protected void button1_click(object sender, eventargs e)
{
label3.text = label3.text + ":" + textbox1.text;
label4.text = label4.text + " : " + textbox2.text;

}
<------------------------------------------------------------------------>

To add new web form.


Website----add new webitem ------webform template. (select asp.net
website-----deafult1.aspx) ----ok
While executing
Select on default1.aspx and click right mouse button
Select property as "set as start page"
<----------------------------------------------------------------------->
2 textboxes
1 label
Protected void button1_click(object sender, eventargs e)
{
string a;
string b;
a = textbox1.text;
b = textbox2.text;
if (a.equals("education") && b.equals("software"))
{
label1.text = "valid username and password";
}
else
{
label1.text = "invalid username and password";
}

}
<------------------------------------------------------------------------->
<h3> select the item for certification</h3>
Radiobutton1---------id(one) and checked ------false
-----------------------(two)
-----------------------(three)
For all the groupnames-----certification

Protected void button1_click(object sender, eventargs e)


{
if (one.checked)
label1.text = "you have selected " + one.text;
else if (two.checked)
label1.text = "you have selected" + two.text;
else
label1.text = "you have selected" + three.text;
}
<---------------------------------------------------------------------------------------------
--------->
Protected void page_load(object sender, eventargs e)
{
listbox1.items.add("india");
listbox1.items.add("australia");

}
protected void submitbtn_click(object sender, eventargs e)
{
If (listbox1.selectedindex > -1)
{
Label1.text = “you have selected: “ + listbox1.selecteditem.text;
}
}
Working with webcontrols in asp.net 2.0
Hyperlink control :

Basically used to navigate from one page to another page :

Drag and drop hyperlink control from the tool box

Key properties :

Id : unique for each control .


Note : no two controls can have same id's

Text : text to displayed on the control

Navigateurl : url/path of the page to navigate

Imageurl : used to set the image to displayed on the hyperlink

** important : hyperlink control doesnot have click event

Button :
Public partial class _default : system.web.ui.page
{
protected void page_load(object sender, eventargs e)
{
}
protected void button1_click(object sender, eventargs e)
{
//to display text informtion on the label set the text
property
lbltext.text = "you clicked on the button";
}
protected void imagebutton1_click(object sender,
imageclickeventargs e)
{
//redirect the page to google website
string redirecturl = "http://www.google.com";
response.redirect(redirecturl);
}
protected void imagebutton2_click(object sender,
imageclickeventargs e)
{
string redirectpage = "~/default2.aspx";
response.redirect(redirectpage);
}
protected void linkbutton1_click(object sender, eventargs e)
{
string redirecturl = "http://www.w3schools.com";
response.redirect(redirecturl);
}
}

Key properties :
Id : identification

Text : used to set/get the text displayed on the control

Key event :

Click : event will be triggered on the server side when user clicks
the button on the client side which posts the page to the server.

Imagebutton :
Redirect to specified website inside the click event

Redirect to the page specified inside the click event

Key properties :

Id : identification

Text : used to set/get the text displayed on the control

Imageurl : used to set the image to be displayed on the control

Key event :

Click : event will be triggered on the server side when user clicks
the button on the client side which posts the
page to the server.
Linkbutton :

This control will have hyperlink appearence along with the click event

Key properties :

Id : identification

Text : used to set/get the text displayed on the control

Key event :

Click : event will be triggered on the server side when user clicks
the button on the client side which posts the page to the server.

<---------------------------------------------------------------------------------------------
----->

Example 4:
Checkbox and radio button

Protected void button1_click(object sender, eventargs e)


{
//inside [set] button
if (checkbox1.checked)
{
textbox1.readonly = true;
}
else
{
textbox1.readonly = false;
}
}
protected void button2_click(object sender, eventargs e)
{
//inside [clear] button
textbox1.text = string.empty;
}
protected void button3_click(object sender, eventargs e)
{
//inside [set] button

if (radiobutton1.checked)
{
textbox2.text = textbox2.text.tolower();
}
else
{
if (radiobutton2.checked)
{
textbox2.text = textbox2.text.toupper();
}
}

//color
if (radiobutton3.checked)
{
textbox2.forecolor = color.blue;
}
else
{
if (radiobutton4.checked)
{
textbox2.forecolor = system.drawing.color.red;
}
else
{
textbox2.forecolor = system.drawing.color.black;
}
}
}
<------------------------------------------------------------------------------------------->
Example 5:
Image control:
Protected void linkbutton1_click(object sender, eventargs e)
{
//inside [more]
//set the descriptionurl of the image control -
"http:\\www.nature-wallpaper.blogspot.com"
response.redirect(image1.descriptionurl);
}
protected void linkbutton2_click(object sender, eventargs e)
{
//inside [flower]
//to set the imageurl programatically
string filepath =
server.mappath("~/app_images/hua006.jpg");
image1.imageurl = filepath;
}
protected void linkbutton3_click(object sender, eventargs e)
{
//inside [default]
string filepath =
server.mappath("~/app_images/vista_metalblue_withlogo_1600x120
0.jpg");
image1.imageurl = filepath;
}
<---------------------------------------------------------------------------------------------
----->
Example 6:
Default.aspx.cs
Protected void button1_click(object sender, eventargs e)
{
string folderpath = textbox1.text.trim();
directoryinfo dir = new directoryinfo(folderpath);
fileinfo[] fileinfo_array = dir.getfiles();

//in order to add the rows and cells (information into cell)
follow these steps
//1. Create a row[s] using tablerow class
//2. Create cell[s] using tablecell class
//3. Add information to cell[s]
//4. Add cell[s] to row[s]
//5. Add row[s] to table control

int index = 1;
foreach (fileinfo file in fileinfo_array)
{
//step1
tablerow r = new tablerow();
//step2.
tablecell cindex = new tablecell();
tablecell cfilename = new tablecell();
tablecell csize = new tablecell();
tablecell ccreated = new tablecell();
//change fore and back color of the cell
cindex.forecolor = system.drawing.color.white;
cindex.backcolor = system.drawing.color.orange;
//step3
cindex.text = index.tostring();
cfilename.text = file.name;
csize.text = file.length.tostring();
ccreated.text = file.creationtime.tostring();
//step4
r.controls.add(cindex);
r.controls.add(cfilename);
r.controls.add(csize);
r.controls.add(ccreated);
//step5
table1.controls.add(r);
index++;
}

}
<---------------------------------------------------------------------------------------------
-------------------------------->
Example 7:

Hidden field control:

Protected void page_load(object sender, eventargs e)


{
if (!ispostback)
{
hiddenfield1.value = datetime.now.tostring();
}
else
{
hiddenfield2.value = datetime.now.tostring();
}
}
protected void button2_click(object sender, eventargs e)
{
lblserverd.text = hiddenfield1.value;
lblpostback.text = hiddenfield2.value;
}

<---------------------------------------------------------------------------------------------
---------------->

List box control:


Protected void page_load(object sender, eventargs e)
{
lblmessage.text = string.empty;
lblitems.text = string.empty;
//add some items into the listbox programatically
if (!ispostback)
{
listitem item1 = new listitem("india", "100");
//item1.selected = true;
listitem item2 = new listitem("canada", "101");
listitem item3 = new listitem("brazil", "103");
listitem item4 = new listitem("usa", "104");

listbox1.items.add(item1);
listbox1.items.add(item2);
listbox1.items.add(item3);
listbox1.items.add(item4);
}
}
protected void button1_click(object sender, eventargs e)
{
//to add item into the listbox
listitem item = new listitem(textbox1.text, textbox2.text);

//add listitem object to listbox


if (!listbox1.items.contains(item))
{
listbox1.items.add(item);
}

}
protected void button2_click(object sender, eventargs e)
{
//check itm is selected or not
if (listbox1.selectedindex != -1)
{
textbox1.text = listbox1.selecteditem.text;
textbox2.text = listbox1.selecteditem.value;
}
}
protected void button3_click(object sender, eventargs e)
{
//check itm is selected or not
if (listbox1.selectedindex != -1)
{
//remove based on selecteditem
//listbox1.items.remove(listbox1.selecteditem);
//remove based on the selectedindex
listbox1.items.removeat(listbox1.selectedindex);
}
}
protected void button4_click(object sender, eventargs e)
{
lblmessage.text = "total items : " +
listbox1.items.count.tostring();
}
protected void button5_click(object sender, eventargs e)
{
listbox1.items.clear();
}
protected void listbox1_selectedindexchanged(object sender,
eventargs e)
{
if (listbox1.selectedindex != -1)
{
textbox1.text = listbox1.selecteditem.text;
textbox2.text = listbox1.selecteditem.value;
}
}
protected void button6_click(object sender, eventargs e)
{
if (listbox1.selectedindex != -1)
{
foreach (listitem item in listbox1.items)
{
if (item.selected)
{
lblitems.text += item.text + "<br/>";
}
}
}
}
<-------------------------------------------------------------------------------------------->
Example 7:
Bulleted list control:

Protected void page_load(object sender, eventargs e)


{
lbllink.text = string.empty;

if (!ispostback)
{
bulletedlist1.displaymode =
bulletedlistdisplaymode.text;
dropdownlist1.autopostback = true;
listbox1.autopostback = true;
//load dropdownlist with displaymodes available
dropdownlist1.datasource =
enum.getnames(typeof(bulletedlistdisplaymode));
//dropdownlist1.databind();
listbox1.datasource =
enum.getnames(typeof(bulletstyle));
//listbox1.databind();
this.databind();
}
}
protected void dropdownlist1_selectedindexchanged(object
sender, eventargs e)
{
//get the display mode
bulletedlist1.displaymode =
(bulletedlistdisplaymode)enum.parse(typeof(bulletedlistdisplaymode)
, dropdownlist1.selectedvalue);
}
protected void listbox1_selectedindexchanged(object sender,
eventargs e)
{
//set the bulletstyle
bulletedlist1.bulletstyle =
(bulletstyle)enum.parse(typeof(bulletstyle), listbox1.selectedvalue);
}
protected void bulletedlist1_click(object sender,
bulletedlisteventargs e)
{
//get the index of the item selected in bulletedlist
int index = e.index;
listitem item = bulletedlist1.items[index];
lbllink.text = item.value;
}
<---------------------------------------------------------------------------------------------
------------------------------------------------->
Checkbox list control:
Protected void page_load(object sender, eventargs e)
{
if (!ispostback)
{
loadfiles(@"c:\windows");
}
}

private void loadfiles(string path)


{
directoryinfo dir = new directoryinfo(path);
fileinfo[] file_info_array = dir.getfiles();
foreach (fileinfo file in file_info_array)
{
//to add items into checklistbox use listitem class
listitem item = new listitem(file.name,
file.length.tostring());

//add item to checklistbox


checkboxlist1.items.add(item);

}
}
protected void linkbutton1_click(object sender, eventargs e)
{
//table1.controls.clear();
long toalfilesize = 0;
tablerow rowheader = new tablerow();
rowheader.backcolor = system.drawing.color.black;
rowheader.forecolor = system.drawing.color.white;
rowheader.font.bold = true;

tablecell chfilename = new tablecell();


chfilename.text = "filename";

tablecell chsize = new tablecell();


chsize.text = "size";

rowheader.controls.add(chfilename);
rowheader.controls.add(chsize);
table1.controls.add(rowheader);

int num = 1;
foreach (listitem item in checkboxlist1.items)
{
if (item.selected)
{

tablerow row = new tablerow();


row.forecolor = system.drawing.color.black;

tablecell cfilename = new tablecell();


tablecell csize = new tablecell();

if ((num % 2) == 0)
{
row.backcolor =
system.drawing.color.whitesmoke;
}
else
{
row.backcolor =
system.drawing.color.white;
}

cfilename.text = item.text;
csize.text = item.value;

row.controls.add(cfilename);
row.controls.add(csize);

table1.controls.add(row);

toalfilesize += int.parse(item.value);
num++;
}

tablerow rowfooter = new tablerow();


tablecell chfooter = new tablecell();
chfooter.columnspan = 2;
rowfooter.backcolor = system.drawing.color.skyblue;
rowfooter.forecolor = system.drawing.color.white;

chfooter.text = "total size : " + toalfilesize.tostring();

rowfooter.controls.add(chfooter);
table1.controls.add(rowfooter);
}
<---------------------------------------------------------------------------------------------
-------->
Drop down list control:
Protected void page_load(object sender, eventargs e)
{
lblmessage.text = string.empty;
lblitems.text = string.empty;
//add some items into the listbox programatically
if (!ispostback)
{
listitem item1 = new listitem("india", "100");
//item1.selected = true;
listitem item2 = new listitem("canada", "101");
listitem item3 = new listitem("brazil", "103");
listitem item4 = new listitem("usa", "104");

dropdownlist1.items.add(item1);
dropdownlist1.items.add(item2);
dropdownlist1.items.add(item3);
dropdownlist1.items.add(item4);
}
}
protected void button1_click(object sender, eventargs e)
{
//to add item into the listbox
listitem item = new listitem(textbox1.text, textbox2.text);

//add listitem object to listbox


if (!dropdownlist1.items.contains(item))
{
dropdownlist1.items.add(item);
}
}
protected void button2_click(object sender, eventargs e)
{
//check itm is selected or not
if (dropdownlist1.selectedindex != -1)
{
textbox1.text = dropdownlist1.selecteditem.text;
textbox2.text = dropdownlist1.selecteditem.value;
}
}
protected void button3_click(object sender, eventargs e)
{
//check itm is selected or not
if (dropdownlist1.selectedindex != -1)
{
//remove based on selecteditem

//dropdownlist1.items.remove(dropdownlist1.selecteditem);
//remove based on the selectedindex

dropdownlist1.items.removeat(dropdownlist1.selectedindex);
}
}
protected void button4_click(object sender, eventargs e)
{
lblmessage.text = "total items : " +
dropdownlist1.items.count.tostring();
}
protected void button5_click(object sender, eventargs e)
{
dropdownlist1.items.clear();
}
protected void button6_click(object sender, eventargs e)
{
}
protected void dropdownlist1_selectedindexchanged(object
sender, eventargs e)
{
if (dropdownlist1.selectedindex != -1)
{
textbox1.text = dropdownlist1.selecteditem.text;
textbox2.text = dropdownlist1.selecteditem.value;
}
}
<---------------------------------------------------------------------------------------------
-->

Radiobox list control:


Protected void page_load(object sender, eventargs e)
{
if (!ispostback)
{
dictionary<string, string> links = new dictionary<string,
string>();
links.add("<a href='#'>download
mirror1</a>","http://www.filedowload1/files/file1.zip");
links.add("<a href='#'>download
mirror2</a>","http://www.filedowload2/files/file1.zip");
links.add("<a href='#'>download
mirror3</a>","http://www.filedowload3/files/file1.zip");

//bind the dictionary to radiobuttonlist


radiobuttonlist1.datasource = links;
//datatextfield specifies the text[item] to be displayed
on the control
radiobuttonlist1.datatextfield = "key";
//datavalufield specifies the value held for each
text[item] displayed on the control
radiobuttonlist1.datavaluefield = "value";
radiobuttonlist1.databind();

//adding items one by one


listitem item = new listitem("<a href='#'>download
mirror4</a>", "http://www.filedowload4/files/file1.zip");
//add the list iem to radiobuttonlist control
radiobuttonlist1.items.add(item);
}

}
protected void button1_click(object sender, eventargs e)
{
//check item selected or not
if (radiobuttonlist1.selectedindex != -1)
{
//get the selected item value
hyperlink1.text = radiobuttonlist1.selecteditem.value;
hyperlink1.navigateurl =
radiobuttonlist1.selecteditem.value;
}
}
<------------------------------------------------------------------------------------------>
Example 8:
Calendar control:
Protected void page_load(object sender, eventargs e)
{

}
protected void calendar1_selectionchanged(object sender,
eventargs e)
{
txtdate.text = calendar1.selecteddate.tolongdatestring();
//txtdate.text = calendar1.selecteddate.toshorttimestring();
}
protected void calendar1_dayrender(object sender,
dayrendereventargs e)
{

int day = e.day.date.day;


if (day >= 17 && day <= 19)
{
e.day.isselectable = false;
e.cell.backcolor = system.drawing.color.red;
e.cell.forecolor = system.drawing.color.white;
e.cell.tooltip = "today is holiday";
}

//adding controls into the calendar


if (day == 15 || day == 20 || day == 25)
{
label lbl = new label();
lbl.id = "lblmessage";
lbl.text = "<br/>b";
lbl.tooltip = "b - birthday";
lbl.forecolor = system.drawing.color.white;
lbl.backcolor = system.drawing.color.skyblue;

//add the control to the cell

e.cell.controls.add(lbl);
}
}
<--------------------------------------------------------------------->
File upload :
Protected void page_load(object sender, eventargs e)
{
lblmessage.text = string.empty;
}
protected void button1_click(object sender, eventargs e)
{
//check file is selected or not
if (fileupload1.hasfile)
{
// retrive the file information
//retrive the filename
lblmessage.text += "filename : " +
fileupload1.filename + "<br/><br/>";
//retrive the file size
lblmessage.text += "size : " +
fileupload1.postedfile.contentlength.tostring() + "<br/><br/>";
//retrive the file mime type
lblmessage.text += "mime type : " +
fileupload1.postedfile.contenttype + "<br/><br/>";

//save the file


string filesavepath = @"d:\uploads\" +
fileupload1.filename;
try
{
fileupload1.saveas(filesavepath);
lblmessage.text += "<b>file uploaded
successfully";
}
catch (exception error)
{
lblmessage.text = "<font color='red'>" +
error.tostring() + "</font>";
}
}
else
{
lblmessage.text = "<font color='red'>*** no file
selected for upload</font>";
}
}
<------------------------------------------------------------------------------------------->
Ado.net:

Sql server provider. To use this system.data.sqlclient namespace is


required.
Ms access uses oledb data provider----> to use this system.data.oledb

Connecting to sql server:

(with in microsoft visual studio 2005)


View-server explorer

Disconnected architechture:

Connection gets disconnected. The retrieved information is stored in a


temporary memory area called "data set"

Data adapter is a bridge between the database and data set.


Data set makes use of method called "fill"
For disconnected architecure the control is "gridview"
<---------------------------------------------------------------------------------------------
------------>
Working
Start---sqlserver 2005 ----sql server management studio----new data
base---right click---enter the data base name ex: db20
Click right mouse button ------select table----
Enter the table details
Ex:
Empno int
Empname varchar(50)
Empsal int
Save the table as emp.

Select grid view on the form.

Note: servername is "computer name"


Protected void page_load(object sender, eventargs e)
{
sqlconnection con = new
sqlconnection("server=ssi-009;uid=sa; pwd=ssi;database=db20");
sqldataadapter da = new sqldataadapter("select * from
emp",con);
dataset ds = new dataset();
da.fill(ds);
gridview1.datasource = ds;
gridview1.databind();
<---------------------------------------------------------------------------------------------
------>

Connected architecture:
Data repeater, data list and data grid view are the controls used to list
the data.
Here it uses open and close method.
Connected architecture and disconnected architecture:

Sql connection sqlconnection


Sqlcommand sqlcommand
sql data adapter
Sql data reader data set

data table
data column
In sql connection there are two methods. Open() and close().

Sql command methods:


Execute reader----------> used to read the data
Execute non query------->insertion, deletion and updation
Execute scalar------------>for manipulation which represents records.

1.returns a result set by way of a data reader object


2. Executes commands have no return value.
3.returns a single value from a database query.
<---------------------------------------------------------------------------------------------
-------------------------------------------->
A data provider is a set of ado.net classes that allows you to access a
specific database,
Execute sql commands, and retrieve data. Essentially, a data provider
is a bridge between your
Application and a data source.
The classes that make up a data provider include the following:
connection: you use this object to establish a connection to a data
source.
command: you use this object to execute sql commands and stored
procedures.
datareader: this object provides fast read-only, forward-only access
to the data retrieved
From a query.
dataadapter: this object performs two tasks. First, you can use it to
fill a dataset (a disconnected collection of tables and relationships)
with information extracted from a datasource.
<---------------------------------------------------------------------------------------------
--------------------------------------->
Sql data reader:
Read( )

Sql data adapter :


Fill()
It opens the connection. It takes the data fill in the data set and
close the connection.
Note: here no need of close() and open()

Disadvantage : execution is slow because too much of temporary


memory in the server.
Data adapter:
It is a bridge between the database and data set. Through which the
data can transfer from data base to data set and reflects the change
made in the data set to data base.

Data provider:
It is used for connecting a database.
Retreiving the data, storing the data in data set. Reading the retriving
data and updating the data base.
They are
Oledb data provider
Sql server data provider namespace : system.data.sqlclient
Odbc.net.provider
<---------------------------------------------------------------------------------------------
----------------------------------->
Ado.net has two types of objects: connection-based and
content-based.
Connection-based objects: these are the data provider objects such as
connection, command,
Dataadapter, and datareader. They execute sql statements, connect
to a database, or fill a
Dataset. The connection-based objects are specific to the type of data
source.
Content-based objects: these objects are really just “packages” for
data. They include the
Dataset, datacolumn, datarow, datarelation, and several others. They
are completely
Independent of the type of data source and are found in the
system.data namespace.
In the rest of this chapter, you’ll learn about the first level of
ado.net—the connection-based
Objects, including connection, command, and datareader.
<---------------------------------------------------------------------------------------------
------------------------------>
Connected architecture:
System.data.sqlclient
Sqlconnection con =new sqlconnection("server=localhost
username=sa,password=;database=pubs");
Con.open();
Sqlcommand cmdselect=new sqlcommand("select authorname from
author",con);
Sqldatareader dataauthor=cmdselect.executereader
While(dataauthor.read())
{
Response.write("<li>");
Response.write(dataauthor[authorname]");
}
Dataauthor.close();
Con.close();
}

or

Sqlconnection con = new sqlconnection("server=ssi-009;uid=sa;


pwd=ssi;database=db20");
con.open();

sqlcommand cmdselect = new sqlcommand ("select * from


emp", con);
sqldatareader dr = cmdselect.executereader();
while (dr.read())
{
response.write ("<li>");
response.write(dr[empname]);
}

gridview1.datasource = dr;
gridview1.databind();
dr.close();
<---------------------------------------------------------------------------------------------
>
Working:
Protected void page_load(object sender, eventargs e)
{
sqlconnection con = new
sqlconnection("server=ssi-009;uid=sa; pwd=ssi;database=db20");
con.open();

string sq ="select count(*) from emp";


Sqlcommand cmd = new sqlcommand(sq, con);
// open the connection and get the count(*) value.
//con.open();
Int numemployees = (int)cmd.executescalar();
Con.close();
response.write (numemployees );
// display the information.
//htmlcontent.text += “<br />total employees: <b>”
+numemployees.tostring() + “</b><br />”;
}
<------------------------------------------------------------------------------------------>
System.data.sqlclient
Private void button1_click()
{
Sqlconnect con;
String strdelete;
Sqlcommand comdelete;
Con=new sqlconnection("server="localhost;username or uid=sa;
pwd=ssi database=pubs");
Strdelete="delete authors where au_id='100';
Comdelete=new sqlcommand(strdelete,con);
Con.open();
Com.delete.executenonquery();
Con.close();
Response.write("records deleted");
}
Private button1_click()
{
Sqlconnection con;
String strupdate;
Sqlcommand cmdupdate;
Con=new
sqlconnection("server=localhost;uid=sa;pwd=ssi;database=pubs");
Strupdate="update author set sfsfs
Comupdate=new sqlcommand(strupdate,con);
Con.open();
Comupdate.executenonquery();
Con.close();
Response.write("records updated");
}

Insert product (productname,unitprice) values('milk',1000);


Same as above
Cmdinsert =new sqlcommand(strinsert,con);
Cmdinsert.parameters.add("productname",txtproductname.text);
Cmdinsert.parameters.add("unitprice",sqldbtype.money).value=txtpri
ce.text
Con.open();
Cmdinsert.executenonquery();
Con.close();

String strupdate;
Sqlcommand cmdupdate;
Int intupdatecnt;
Con=new sqlconnection;
Strupdate="update authors set phone=@phone;
Cmdupdate=new sqlcommand(strupdate,con);
Cmdupdate.parameters.add("@phone",txtphone);
Cmdupdate.parameters.add("@firstname",txtfirstname);
Cmdupdate.parameters.add("@lastname",txtlastname);
Con.open();
Intupdatecnt=cmdupdate.executenonquery();
Con.close();
Lblresults.text=intupdatecnt+"record updated";
Button_click
Sqlconnection con;
String strdelete;
Sqlcommand cmddelete;
Int intdelectcnt;
Con=new sqlconnection(" ------------
Strdelete="delete authors where lastname=@lastname;
Cmddelete=new sqlcommand(strdelete,con);
Cmddelete.parameters.add("@lastname",txtlastname.text);
Con.open();
Intdeletecnt=cmddelete.executenonquery();
Con.close();
Lblresult.text=intdeletecnt +"records deleted";

You might also like