C#
C#
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
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
Logical operator:
&& (logical and)
|| (logical or)
! (logical not)
|| (logical or)
Any one of the condition must be true to obtain final value true.
! (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
Pre increment:
A=10
B=++a
A=11
B=11
Post increment:
A=10
B=a++
B=10
A=11
C= (a>b)?a:b;
Bitwise operator:
It operates on binary digits.
They are
& , | , ^ , << , >>
Comma operator:
Int a,b;
To display a message :
Console-------------> it is a class.
Writeline------------> method
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 : ");
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);
console.foregroundcolor = consolecolor.white;
console.backgroundcolor = consolecolor.red;
Console.write("a = ");
int a = int.parse(console.readline());
console.write("b = ");
int b = int.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;
}
<----------------------------------------------------------------------------------------->
default:
console.writeline("choice not found");
break;
}
<------------------------------------------------------------------------->
Strings:
Built in functions:
The followings are the functions of string class.
Startswith()
Endswith()
Equals()
Length()
Replace()
//declaration
string s = "welcome to strings in c#";
console.writeline("length : {0}", s.length);
<----------------------------------------------------------------------------------------->
Startswith() : this function is used to check string that starts with.
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:
For loop
For(initialization;condition;updation)
<------------------------------------------------------------------------------->
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 sample
{
Int x;---------------------------->data member or property
Void getdata();----------->function or behaviour
}
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
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.
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
{
}
}
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:
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();
}
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(int x, int y)
{
this.x = x; // this - > self reference of the class
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
//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;
emp1.displayinformation();
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.
<--------------------------------------------------------------------------------------->
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() { }
}
}
<------------------------------------------------------------------------->
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 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:
Interface:
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();
}
}
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()
{
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());
int c = a / b;
}
}
}
<---------------------------------------------------------------------------------------------
------------------------------------->
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);
finally
{
console.writeline("executing finally block");
}
}
}
}
<-------------------------------------------------------------------------------->
Boxing and unboxing
//boxing
object obj = i; //heap
// unboxing
float y = (float)obj1; // unboxing
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)
{
//console.clear();
console.writeline("before\n");
foreach (int element in list)
{
console.writeline(element);
}
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");
}
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);
}
}
}
}
}
}
}
<--------------------------------------------------------------------->
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");
}
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:
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" };
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();
}
}
}
}
<---------------------------------------------------------------------------------------------
-------------------------------------------------------------------------->
Using system.collections;
Namespace example3
{
class program
{
static void main(string[] args)
{
//arraylist - list
//hashtable - dictionary
//sortedlist
//stack
//queue
}
}
<---------------------------------------------------------------------------------------->
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();
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();
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:\");
}
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);
}
}
}
<---------------------------------------------------------------------------------------------
>
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
Advantages of asp.net:
Note:
Web server which is used to execute web applictions such as html,
java script, asp.net and xml
Csharp
Note :
Standard controls:
These are web server controls.
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.
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.
<------------------------------------------------------------------------->
}
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)
{
trace.isenabled = true;
}
<------------------------------------------------------------------------->
Protected void button1_click(object sender, eventargs e)
{
label3.text = label3.text + ":" + textbox1.text;
label4.text = label4.text + " : " + textbox2.text;
}
<------------------------------------------------------------------------>
}
<------------------------------------------------------------------------->
<h3> select the item for certification</h3>
Radiobutton1---------id(one) and checked ------false
-----------------------(two)
-----------------------(three)
For all the groupnames-----certification
}
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 :
Key properties :
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
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
Key properties :
Id : identification
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
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
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:
<---------------------------------------------------------------------------------------------
---------------->
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);
}
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:
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");
}
}
}
}
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;
rowheader.controls.add(chfilename);
rowheader.controls.add(chsize);
table1.controls.add(rowheader);
int num = 1;
foreach (listitem item in checkboxlist1.items)
{
if (item.selected)
{
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++;
}
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);
//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;
}
}
<---------------------------------------------------------------------------------------------
-->
}
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)
{
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/>";
Disconnected architechture:
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:
data table
data column
In sql connection there are two methods. Open() and close().
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
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 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";