Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 64

DOT NET

TECHNOLOGY
(Lab Manual)

Information
Technology
Department

V.V.P.
Engineering
College

DOT NET TECHNOLOGY Lab, An Inspiring place


Dot Net platform has asked "what do developers waste time doing", and tried to improve
developer performance. A large and well documented class library helps avoid re-inventing
the same wheel many times over. Inter-operability between code in number of languages is
made trivial. The C# language was created alongside the .Net platform. It could be
considered the "native" language of .Net providing access to the vast majority of language
features that the .Net runtime is optimized to support. It takes the best bits of Java, C and C+
+, producing a language with the clear object oriented programming constructs of Java along
with useful features such as enumerations and structures from C. This lab manual helps
students for practical guidance in laboratory.
Latest Manual Prepared By :-

Prof. AVani.R.Vasant
Prof. Priti P. Mehta

Lab incharge :-

Prof. Priti P. Mehta

Founder Member of Lab :-

Prof. Avani R. Vasant


Prof. N.G.Karelia
Prof. M.D.Titiya

HOD of Information Technology Department


( Ass. Prof . AVANI.R.VASANT )

The C# Language
C# (pronounced C-Sharp) is no doubt the language of choice in the .Net environment. It is a
whole new language free of the backward compatibility curse with a whole bunch of new,
exciting and promising features. It is an Object Oriented Programming language and has at
its core, many similarities to Java, C++ and VB. In fact, C# combines the power and efficiency
of C++, the simple and clean OO design of Java and the language simplification of Visual
Basic.
Like Java, C# also does not allow multiple inheritance or the use of pointers (in
safe/managed code), but does provide garbage memory collection at runtime, type and
memory access checking. However, contrary to JAVA, C# maintains the unique useful
operations of C++ like operator overloading, enumerations, pre-processor directives, pointers
(in unmanaged/un-safe code), function pointer (in the form of delegates) and promise to have
template support in the next versions. Like VB, it also supports the concepts of properties
(context sensitive fields). In addition to this, C# come up with some new and exciting features
such as reflection, attributes, marshalling, remoting, threads, streams, data access with
ADO.Net and more
The .Net Architecture and .Net Framework
In the .Net Architecture and the .Net Framework there are different important terms and
concepts which we will discuss one by one:The common Language Runtime (CLR)

The most important concept of the .Net Framework is the existence and functionality of .Net
Common Language Runtime (CLR), also called .Net Runtime for short. It is a framework
layer that resides above the OS and handles the execution of all the .Net applications. Our
programs dont directly communicate with the OS but go through the CLR.

Our .Net Application

Common Language Runtime (CLR)

Windows OS

MSIL (Microsoft Intermediate Language) Code


When we compile our .Net program using any .Net compliant language (such as C#, VB.Net
or C++.Net) our source code does not get converted into the executable binary code, but to
an intermediate code known as MSIL which is interpreted by Common Language Runtime.
MSIL is operating system and hardware independent code. Upon program execution, this
MSIL (intermediate code) is converted to binary executable code (native code). Cross
language relationships are possible a the MSIL code is similar for each .Net language.

Code in
any .Net
Language

MSIL
Code

Executable
Native Code

The Common Type System (CTS)


.Net also defines a common Type System (CTS). Like CLS, CTS is also a set of standards.
CTS defines the basic data types that IL understands. Each .Net compliant language should
map its data types to these standard data types. This makes it possible for the 2 languages to
communicate with each other by passing/receiving parameters to and from each other. For
example, CTS defines a type, Int32, an integral data type of 32 bits (4bytes) which is mapped
by C# through int and VB.Net through its Integer data type.

Garbage Collection (GC)

CLR also contains the Garbage Collector (GC), which runs in a low-priority thread and
checks for un-referenced, dynamically allocated memory space. If it finds some data that is
no longer referenced by any variable/reference, it re-claims it and returns it to the OS. The
presence of a standard Garbage Collector frees the programmer from keeping track of
dangling data. Ask any C++ programmer how big a relief it is!
The .Net Framework

Our .Net Applications


(WinForms, Web Applications, Web Services)
Data (ADO.Net) and XML Library

Framework Class Library (FCL)


(IO, Streams, Sockets, Security, Reflection, UI)
Common Language Runtime (CLR)
(Debugger, Type Checking, JIT, exceptions, GC)
Windows OS

The .Net Framework is the combination of layers of CLR, FCL, Data and XML Classes and
our Windows, Web applications and Web Services. A diagram of the .Net Framework is
presented below for better understanding.

.NET FRAMEWORK PROCESS

C# Source Code

Compiler
CSC

MSIL EXE or DLL

Execution
JIT Compiler

Type Verification

Compiles into

Managed Native
Code

CLR
Runtime

Final Output

C# compared to C++
In terms of performance and efficiency in the use of memory and other resources, C++ does
outclass C#. But are performance and speed the only measure when it comes to choosing a
development environment. No! C++ is no doubt a very complex, abstract and low-level
language to program. It burdens programmer with many responsibilities and less support.
Another problem with C++ is that it is a vast language at its core, with too many
Just In Time Compilers (JITers)
When our IL compiled code needs to be executed, the CLR invokes the JIT compiler, which
compile the IL code to native executable code (.exe or .dll) that is designed for the specific
machine and OS. JITers in many ways are different from traditional compilers as they
compile the IL to native code only when desired; e.g., when a function is called, the IL of the
function's body is converted to native code just in time. So, the part of code that is not used
by that particular run is never converted to native code. If some IL code is converted to
native code, then the next time it's needed, the CLR reuses the same (already compiled)
copy without re-compiling. So, if a program runs for some time (assuming that all or most of
the functions get called), then it won't have any just-in-time performance penalty.

As JITers are aware of the specific processor and OS at runtime, they can optimize
the code extremely efficiently resulting in very robust applications. Also, since a JIT compiler
knows the exact current state of executable code, they can also optimize the code by inlining small function calls (like replacing body of small function when its called in a loop,
saving the function call time). Although Microsoft stated that C# and .Net are not competing
with languages like C++ in efficiency and speed of execution, JITers can make your code
even faster than C++ code in some cases when the program is run over an extended period
of time (like web-servers).
The Framework Class Library (FCL)
The .Net Framework provides a huge Framework (or Base) Class Library (FCL) for common,
usual tasks. FCL contains thousands of classes to provide access to Windows API and
common functions like String Manipulation, Common Data Structures, IO, Streams, Threads,
Security, Network Programming, Windows Programming, Web
Programming, Data Access, etc. It is simply the largest standard library ever shipped with
any development environment or programming language. The best part of this library is they
follow extremely efficient OO design (design patterns) making their access and use very
simple and predictable. You can use the classes in FCL in your
program just as you would use any other class. You can even apply inheritance and
polymorphism to these classes.

The Common Language Specification (CLS)


Earlier, we used the term '.Net Compliant Language' and stated that all the .Net compliant
languages can make use of CLR and FCL. But what makes a language a '.Net compliant'
language. The answer is the Common Language Specification (CLS). Microsoft has
released a small set of specifications that each language should meet to qualify as a .Net
Compliant Language. As IL is a very rich language, it is not necessary for a language to
implement all the IL functionality; rather, it merely needs to meet a small subset of CLS to
qualify as a .Net compliant language. This is the reason why so many languages (procedural
and OO) are now running under the .Net umbrella. CLS basically addresses language
design issues and lays down certain standards. For instance, there shouldn't be any global
7

function declarations, no pointers, no multiple inheritance and things like that. The important
point to note here is that if you keep your code within the CLS boundary, your code is
guaranteed to be usable in any other .Net language.
IL Dis-Assembler(ILDASM)
Generated MSIL Code looks like an assembly code / Language. To see the MSIL output by
the .NET compilers, Microsoft has included a dis-assembler named the Microsoft .NET
Framework IL Dis assembler (ILDASM) to enable you to open a .NET executable file(.exe
or .dll).
Overview of ADO.Net.

ADO.net is a set of libraries included in the Microsoft .net framework that help you

communicate with various data stores from .net applications.

ADO.net provides consistent access to data sources such as Microsoft SQL server, as

well as data sources exposed to through OLEDB and XML.data

sharing consumer

applications can use ADO.Net to connect these data sources and retrieve manipulate &
update data.
History of ADO.Net.

All those developers who have been using ADO might ask isnt that what ADO is for?

ADO(active data object).

Visual basic has introduced users with its each successive version of it to a new data

access model.

Visual Basic 3 included data access objects (DAO).

Visual Basic 4 introduced developers to remote data objects (RDO).

Visual Basic 5 and visual studio 97 included ODBC direct

Visual Basic 6 & visual studio introduced ADO.


8

DAO was designed to communicate with local file based databases but VB developers

wanted to talk to server based databases like Microsoft SQL & Oracle. It allows developers to
communicate with such databases but developers craved more control and better
performance.

So,The VB development team created RDO to give the developers a fast, light weight

data access layer designed to talk to larger servers based databased. But now the problem
was they wanted the power of RDO but did not wanted to give up with DAO.

So, Microsoft created ODBC direct to give them best of both worlds.

Now with the development of the internet the developers wanted data access model that

could use more easily in a server side scripting that would allow them to pass data structures
from server to client & back and so ADO was born.

ADO had served the developers in the post &had build powerfull applications but it had

also many disadvantages & many nooks and corners.

More & more developers wanted to work with XML features, ADO was not built to work

with XML data. Microsoft might add more XML features to the future releases of ADO but
ADO will never handle XML data as efficiently as ADO.net does. Bcoz ADO.net was
designed with XML keeping in mind while ADO was not.

ADO does not allow you to separate the schema information from actual data.

The ADO cursor engine makes it possible to pass disconnected ADO record set objects

between different tiers of your application, but you cannot combine the contents of multiple
record set objects.

ADO allows you to submit cached changes to databases but it does not give you control

over the logic used to submit updates.

Also ADO engine does not provide a way to submit pending changes to your databases

via stored procedures.

ADO was based on COM based application development but with the development of

common language runtime & .net framework Microsoft designed ADO.net.


9

ADO.net is designed to combine the best feature of its predecessor while adding feature

requested more frequently by development like greater XML support, easier disconnected
data access, more control over updates and greater flexibility.
Getting Started with C-Sharp
First of all let me welcome you to the world of this new programming language. I hope you
will have a basic idea about Object Oriented Programming language because many
languages like Java, C++ have come by the past 5 years. However there will be no difficulty
in learning this language if you are a fresher, because this tutorial and the coming ones will
explain all the concepts and features right from the beginning.
Wherever required I explained the features involved in C-sharp by comparing them with Java.
This will ensure smooth progress for experienced Programmers. I recommended you to
install the appropriate softwares outlined in the next section before learning this new
language.
Basic requirements needed to begin C-sharp Programming
1.

.NET Framework Software Development kit and

2.

An Editor (like notepad or DOS Editor) to write Source Codes.

Optional Requirements:
1.

Visual C# .NET or

2.

Visual C++ 6.0 included with Visual Studio 6.0

How to Compile and execute a C# Program:


On command Prompt (SDK)
CSC Hello.cs
it will generate hello.exe
To execute a program.
On command prompt type Hello will generate the output from the file.
10

Two Phases of compilation:


First Phase( use of csc) converts .cs file into.exe file which is often known as an
assembly.
The code within the assembly is known as the managed code (MSIL codes).
The Managed code can only be executed under the .net environment. So you cannot
run .exe on a PC which doesnt have .net framework installed.
Second phase of compilation is known as just-in-time compilation(JIT)
JIT converts MSIL code into native machine code.
For each platform CLR is different and JIT leads to performance improvement.
Normally when a program is compiled the whole source code is converted into .exe at
the same time.
.net CLR compiler(JIT) only , execute that portion of the application which is currently
being used (thats why just-in-time).
When portion of an application is accessed for the in memory.
Now, it Remain in memory until the application is in memory.
By not, compiling the whole application at the same time leads to quicker
response when size of the application is very large.
Important points:
Your C# executable program resides in some class.
The entry point to program is the static void main() with void return type.
C# is a case sensitive language so void and void are different.
You dont need to save your program with same file name as of your class containing
main() method.

11

Ass : 1
Answer the following Questions
a. What is .NET? Explain its architecture and .NET Framework process in detail
b. Give advantages of CLR
c. Explain CLS
d. Explain CTS
e. What is Garbage Collections?
f.

NOTE:

What is ILDASM.

Above questions can be very well answered from the given Introduction.

12

Arrays
We wont say too much about arrays because you are already aware with the concept.
However well give you just enough syntax here that you can code 1-dimensional arrays.
Arrays in C# are declared by fixing a set of square brackets to the end of the variable type of
the individual elements (note that all the elements in an array must be of the same data type).
Arrays in C# use square brackets, not parentheses. C++ users will be familiar with the
square brackets, but should check the code we present here carefully because C#
syntax for actually declaring array variables is not the same as C++ syntax. For
example, while int represents a single integer,
int [] represents an array of integers:
int[] integers;
To initialize the array with specific dimensions, we can use the new keyword, giving the size
in the square brackets after the type name:
// Create a new array of 32 ints
int[] integers = new int[32];
All arrays are reference types and follow reference semantics. Hence, in this code, even
though the individual elements are primitive value types, the integers array is a reference
type. Hence if we later write
int [] copy = integers;
This will simply assign the variable copy to refer to the same arrayit wont create a new
array. To access an individual element within the array, we use the usual syntax, placing the
index of the element in square brackets after the name of the array. All C# arrays use zerobased indexing, so we can reference the first variable with the index zero:
integers[0] = 35;
Similarly, we reference the 32 element value with an index value of 31:
integers[31] = 432;
C#s array syntax is flexible. In fact, C# allows us to declare arrays without initializing them,
so that the array can be dynamically sized later in the program. With this technique, we are
basically creating a null reference, and later pointing that reference at a dynamically allocated
stretch of memory locations requested with the new keyword:
int[] integers;
integers = new int[32];
You can find out how many elements are in any array by using this syntax:
int numElements = integers.Length; // integers is any reference to an array.

13

Ass : 2
Create class SingleDimArryApp with int () number as its data members and create an
array of dimension 6 starting from o store the squares of the number and print on the
console all the elements of the arry.
using System;
class sigle_dimensional_array
{
int []s= new int [6];
int []sq= new int [6];
int i;
public int[] Number
{
set
{ s=value;}
}
public void square()
{
for(i=0;i<6;i++)
sq[i]=s[i]*s[i];
}
public void disp()
{
for(i=0;i<6;i++)
Console.WriteLine("Square of {0}: {1}",s[i],sq[i]);
}
}
class array_application
{
static void Main()
{
int []S= new int [6];
int i;
sigle_dimensional_array sa= new sigle_dimensional_array();
sa.Number=S;
Console.WriteLine("Enter any six numbers...");
for(i=0;i<6;i++)
S[i]=Convert.ToInt32(Console.ReadLine());
sa.square();
Console.WriteLine();
Console.WriteLine("Square of Given Numbers...");
Console.WriteLine();
sa.disp();
Console.ReadLine();
}
}
14

Ass : 3
Modify the above program use jagged array.
using System;
class Jagged_array
{
int [][]s= new int [2][];
int [][]sq=new int [2][];
int i,j;
public int[][] Number
{
set
{s=value;}
}
public int[][] Square
{
set
{sq=value;}
}
public void disp()
{
for(i=0;i<2;i++)
for(j=0;j<sq[i].Length;j++)
Console.WriteLine("Square of {0} is: {1}",s[i][j],sq[i][j]);
}
}
class array_aaplication
{
static void Main()
{
Jagged_array sa=new Jagged_array();
int [][]S= new int [2][];
int [][]Sq=new int [2][];
int n,i,j;
sa.Square=Sq;
sa.Number=S;
for(i=0;i<2;i++)
{
Console.WriteLine();
Console.WriteLine("Enter the number of column...");
n=Convert.ToInt32(Console.ReadLine());
Console.WriteLine();
Console.WriteLine("Enter the {0} values...",n);
S[i]= new int [n];
Sq[i]= new int [n];
for(j=0;j<n;j++)
{
S[i][j]=Convert.ToInt32(Console.ReadLine());
15

Sq[i][j]=S[i][j]*S[i][j];
}
}
Console.WriteLine();
sa.disp();
}
}

16

Static Variables
Its important to understand that by default each instance of a class (each object) has its own
set of all the fields youve defined in the class. For example, in the following snippet the
instances karli and julian each contain their own string called password:
Authenticator julian = new Authenticator();
Authenticator karli = new Authenticator();
karli.ChangePassword(OldKarliPassword, NewKarliPassword);
julian.ChangePassword(OldJulianPassword, NewJulianPassword);
Changing the password in karli has no effect on the password in julian, and vice versa
(unless the two references happen to be pointing to the same address in memory, which is
something well come to later). This situation resembles Figure A-1.

There are some cases in which this might not be the behavior you want. For example,
suppose we want to define a minimum length for all passwords (and therefore for all of the
password fields in all instances) in our Authenticator class. We do not want each password to
have its own minimum length. Therefore, we really want the minimum length to be stored only
once in memory, no matter how
many instances of Authenticator we create.
To indicate that a field should only be stored once, no matter how many instances of the class
we create, we place the keyword static in front of the field declaration in our code:
public class Authenticator
{
private static uint minPasswordLength = 6;
private string password = ;
Storing a copy of minPasswordLength with each Authenticator instance not only wastes
memory but also causes problems if we want to be able to change its value! By declaring the
field as static, we ensure that it is only stored once, and this field is shared among all
instances of the class. Note that in this code snippet we also set an initial value.
Fields declared with the static keyword are referred to as static fields or static data, while
fields that are not declared as static are referred to as instance fields or instance data.
Another way of looking at this is that an instance field belongs to an object, while a static field
belongs to the class. If a field has been declared as static, then it exists when your program is
running from the moment that the particular module or assembly containing the definition of
the class is loadedthat is as soon as your code tries to use something from that assembly,
so you can always guarantee a static variable is there when you want to refer to it. This is
17

independent of whether you actually create any instances of that class. By contrast, instance
fields only exist when there are variables of that class currently in scopeone set of instance
fields for each variable.

18

Ass : 4
Define a class InstCount with a static member instance count. Increment the value of
instance count, every time as instance is created. Create more than one instance of this class
and display the value of the instancecount.
using System;
namespace usestat
{
class InstCount
{
static int count = 0;
int b = 0;
public InstCount()
{
count++;
}
public static void disp()
{
Console.WriteLine("The number of objects created are " +count);
//Console.WriteLine(b); // not allowed
}
}
class ex
{
static void Main(string[] args)
{
InstCount p1 = new InstCount();
// p1.disp();// cannot be used using instance
InstCount p2 = new InstCount();
//p2.disp();
InstCount.disp();
}
}
}

19

Ass : 5
Define a class with 2 datamembers: num1 as constant and num2 as readonly. Display the
values of both on the console and state the difference between them.
Difference between Constant and Read-Only
Constant
Read-Only
It is used with Value Types , Cannot be used It is used with Reference type varibles only
with Reference types
Constat variables value must be assigned at Value can be assigned at Runtime also.
Compile time.
using System;
namespace useconstread
{
class app
{
const int b = 20;
readonly int c;
public app()
{
}
public app(int a)
{
c = a + 2;
}
public static void disp()
{
Console.WriteLine("value of constant variable b = {0}", b);
}
public void show()
{
Console.WriteLine("value of ReadOnly variable c = {0}", c);
}
}
class ex
{
static void Main(string[] args)
{
app a1 = new app();
app a2 = new app(10);
app.disp();
a2.show();
}}}
Ass : 6
20

Explain Boxing and UnBoxing with Example.


Boxing:
Converting Value type to reference type is called boxing.
UnBoxing:
Converting refernce type to value type is called un-boxing.
using System;
class Test
{
public static void Main()
{
int i=42;
object o = i;
Console.WriteLine(i + " , " +(Int32)o);
}
}
Properties
Properties are unusual in that they represent an idea that C# has taken from Visual Basic, not
from C++/Java. The idea of a property is that it is a method or pair of methods that are
dressed to look like a field as far as any client code is concerned. A good example of this is
the Height property of a Windows Form. Suppose you have the following code:
// mainForm is of type System.Windows.Forms
mainForm.Height = 400;
On executing this code, the height of the window will be set to 400 and you will see the
window resize on the screen. Syntactically, the above code looks like were setting a field, but
in fact we are calling a property accessor that contains code to resize the form.

21

To define a property in C#, we use the following syntax.


public string SomeProperty
{
get
{
return This is the property value;
}
set
{
// do whatever needs to be done to set the property
}
}
The get accessor takes no parameters and must return the same type as the declared
property. You should not specify any explicit parameters for the set accessor either, but the
compiler assumes it takes one parameter, which is of the same type again, and which is
referred to as value. As an example, the following code contains a property called ForeName,
which sets a field called foreName, and which applies a length limit.
private string foreName;
public string ForeName
{
get
{
return foreName;
}
set
{
if (value.Length > 20)
// code here to take error recovery action
// (eg. throw an exception)
else
foreName = value;
}
}
Note the naming convention used here. We take advantage of C#s case sensitivity by using
the same name, Pascal-cased for the public property and camel-cased for the equivalent
private field if there is one. This is standard practice. Some developers prefer to use field
names that are prefixed by an underscore: _foreName; this provides an extremely convenient
way of identifying fields. In C#, the write accessor is always identified with the keyword, set.
Read-only and write-only properties
It is possible to create a read-only property by simply omitting the set accessor from the
property definition.
Thus, to make ForeName read-only in the previous example:

22

Objects and Types


private string foreName;
public string ForeName
{
get
{
return foreName;
}
}
It is similarly possible to create a write-only property by omitting the get accessor. However,
this is regarded as poor programming practice because it could be confusing to authors of
client code. In general, it is recommended that if you are tempted to do this, you should use a
method instead.

23

Ass :7
Define a class student with MarksofCN, MarksofNET, MarksofSAD, name,per,avg as its data
member. Enter the marks, find average & percentage for that use Properties and display it.
using System;
namespace cs2
{
class student
{
string name;
int age;
int marksofMaths, marksofEnglish, marksofScience;
int totalmarks = 300;
int obtainedmarks;
double per;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public int Totalmarks
{
get
{
return totalmarks;
}
}
public int Age
{
get
{
return age;
}
set
{
age = value;
}
}
public int MarksofMaths
24

{
get
{
return marksofMaths;
}
set
{
marksofMaths = value;
}
}
public int MarksofEnglish
{
get
{
return marksofEnglish;
}
set
{
marksofEnglish = value;
}
}
public int MarksofScience
{
get
{
return marksofScience;
}
set
{
marksofScience = value;
}
}
public double Per
{
get
{
return per;
}
set
{
per = value;
}
}
public int Obtainedmarks
{
25

get
{
return obtainedmarks;
}
set
{
obtainedmarks = value;
}
}
}
class Program
{
static void Main(string[] args)
{
student s1 = new student();
s1.Name = "Einstein";
s1.Age = 20;
s1.MarksofMaths = 99;
s1.MarksofEnglish = 80;
s1.MarksofScience = 96;
s1.Obtainedmarks = s1.MarksofEnglish + s1.MarksofMaths + s1.MarksofScience;
s1.Per = (double)s1.Obtainedmarks / s1.Totalmarks *100;
Console.WriteLine("Name={0},Age={1},Percentage={2}", s1.Name, s1.Age, s1.Per);
}
}
}

26

Ref parameters
Passing variables by value is the default. We can, however, force value parameters to be
passed by reference. To do so, we use the ref keyword. If a parameter is passed to a method,
and if the input argument for that method is prefixed with the ref keyword, then any changes
that the method makes to the variable will affect the value of the original object:
static void SomeFunction(int[] ints, ref int i)
{
ints[0] = 100;
i = 100; // the change to i will persist after SomeFunction() exits
}
We will also need to add the ref keyword when we invoke the method:
SomeFunction(ints, ref i);
Adding the ref keyword in C# serves the same purpose as using the & syntax in C++ to
specify passing by reference. However, C# makes the behavior more explicit (thus hopefully
preventing bugs) by requiring the use of the ref keyword when invoking the method.
Finally, it is also important to understand that C# continues to apply initialization requirements
to parameters passed to methods. Any variable must be initialized before it is passed into a
method, whether it is passed in by value or reference.
Out parameters
In C-style languages, it is common for functions to be able to output more than one value
from a single routine. This is accomplished using output parameters, by assigning the output
values to variables that have been passed to the method by reference. Often, the starting
values of the variables that are passed by reference are unimportant. Those values will be
overwritten by the function, which may never even look at any previous value.
It would be convenient if we could use the same convention in C#. However, C# requires that
variables be initialized with a starting value before they are referenced. Although we could
initialize our input variables with meaningless values before passing them into a function that
will fill them with real, meaningful ones, this practice seems at best needless and at worst
confusing.
However, there is a way to short-circuit the C# compilers insistence on initial values for input
arguments. This is achieved with the out keyword. When a methods input argument is
prefixed with out, that method can be passed a variable that has not been initialized. The
variable is passed by reference, so any
changes that the method makes to the variable will persist when control returns from the
called method. Again, we also need to use the out keyword when we call the method, as well
as when we define it:

27

static void SomeFunction(out int i)


{
i = 100;
}
public static int Main()
{
int i; // note how i is declared but not initialized
SomeFunction(out i);
Console.WriteLine(i);
return 0;
}
The out keyword is an example of something new in C# that has no analogy in either Visual
Basic or C++, and which has been introduced to make C# more secure against bugs. If an
out parameter isnt assigned a value within the body of the function, the method wont
compile.

28

Ass :8
Define a class color with red, green and blue as its data members.Using ref and out
keywords test the output of the method, Getcolors (Int, int, int) where the parameters of
Getcolors method is colors-red, green, and blue.
using System;
class color
{
public color()
{
this.red = 0;
this.green = 127;
this.blue = 255;
}
protected int red;
protected int green;
protected int blue;
public void getcolor(ref int red, ref int green, ref int blue)
{
red = this.red;
green = this.green;
blue = this.blue;
}
}
class application
{
static void Main()
{
color c = new color();
int r = 0;
int g = 0;
int b = 0;
c.getcolor(ref r, ref g, ref b);
Console.WriteLine("Red={0},Green={1},Blue={2}", r, g, b);
}
}

29

Ass :9
Define a class Addition with three datamembers. Defineoverloaded method add () with one,
two and three arguments tostudy method overloading.
using System;
namespace usemethodoverload
{
class adder
{
public int add(int x, int y)
{
return (x+y);
}
public int add(int x, int y,int z)
{
return (x + y+z);
}
public float add(float x, float y)
{
return (x + y);
}
public string add(string x, string y)
{
return (x + y);
}
public decimal add(decimal x, decimal y)
{
return (x + y);
}
}
class app
{
static void Main(string[] args)
{
adder a = new adder();
Console.WriteLine(a.add(2,3));
Console.WriteLine(a.add(2, 3,5));
Console.WriteLine(a.add(2.4F,3.2F));
Console.WriteLine(a.add("Hello","Hi"));
Console.WriteLine(a.add(4.5M, 2.4M));
} }

30

Ass :10
Write a program to illustrate polymorphism using the following class: class
Employee{
protected string Name;}and create two classes ContractEmployee and
SalariedEmplyee derived from Employee class and create a method called CalaulatePay()
that will canculate the pay of the employee depending whether he/she is ContractEmployee
of SalariedEmployee.
using System;
class employee
{
protected int basics;
protected string name;
protected double DA;
protected double HRA;
protected double Totpay;
public employee(string name, int basics)
{
this.name = name;
this.basics = basics;
this.DA = basics * 0.15F;
this.HRA = basics * 0.26F;
}
public virtual void calculatepay()
{
this.Totpay = this.basics + this.DA + this.HRA;
Console.WriteLine("Salary of the employee {0} is:{1}", name, Totpay);
}
}
class manager:employee
{
int sppay;
int empno;
public manager(string name,int basics,int sppay,int empno):base(name,basics)
{
this.sppay=sppay;
this.empno=empno;
}
public manager(string name,int basics):base(name,basics)
{
}
public override void calculatepay()
{
this.Totpay=this.basics+this.DA+this.HRA+(this.sppay*this.empno);
Console.WriteLine("Salary of the manager {0} is:{1}",this.name,this.Totpay);
}
}
class clerk:manager
31

{
int docno;
public clerk(string name,int basics,int docno):base(name,basics)
{
this.docno=docno;
}
public override void calculatepay()
{
this.Totpay=this.basics+this.DA+this.HRA+(this.docno*5);
Console.WriteLine("Salary of the Clerk {0} is:{1}",this.name,this.Totpay);
}
}
class application
{
static void Main()
{
employee [] e=new employee [3];
e[0]=new employee("scott",10000);
e[1]=new manager("martine",20000,3500,12);
e[2]=new clerk("thomas",7000,15);
e[0].calculatepay();
e[1].calculatepay();
e[2].calculatepay();
}
}

32

Oledb connection object propertices.


1. Connection string property:It controls how the connection object will attempt to connect to your data source. You can set
this property only when your connection is not connected to your data source when it is
connected to your data source the property is read only.
2. Connection time out property:It indicates the amount of time in second, that the OLEDB provider will wait on an attempt to
connect to your data source before timing out. This property is read only and not all OLEDB
providers support this feature like OLEDB provider for jet and oracle database etc. if you set
a value for the connect time out attribute in your connection setting and the OLEDB provider,
you are using does not support this feature, you will throw an exception when you call the
open method of the OLEDB connection.
3. Database and data source properties:The terms database and data source are often used inter changeably as they are used. But
lets make a difference between the two. If you are working with a server based data store
such as SQL server or oracle, the data source property will return the name of the machine
acting as the server. For file based databases such as access the data source property will
return the location of the data file.
Provider=SQLOLEDB: data source=(local )\net SDK; initial catalog =Northwind; Trusted
connection = yes; connect time out = 11;
The database property designed for data sources that support multiple databases such as
SQL server. When we examined SQL server connection strings we specified. The data base
on the server we wanted to connect to in the initial catalog attribute of all the connection
string.
4. Provider property:It lets you determine the OLEDB provider specified in the connection string. The ODBC
connection property exposes a similar property. Driver which returns the name of the ODBC
driver specified in the connection string. Because of the SQL connection class supports
connecting only to SQL server databases. This is no need for a property.
33

5. Server version property :Server version property to ensure you doesnt make unsupported calls to the server. The
source version property returns a string containing the version of the database to which you
are connected.
Eg. String strcon = provider = Microsoft.jet.oledb.4.0; Data source = (local)\\ netSDK : +
initial catalog =northwind ; trusted_connection = yes;;
OLEDB connection on = new OLEDB connection (strcon);
Cn.open();
If(server version >= 08)
{
run your query here.
}
6. State property.
It returns the current state of the connection as a member of the connection state
enumeration in the system data namespace.

34

Ass :11
Write a program to show Oledb connection object propertices.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
OleDbConnection con = new
OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\\db1.mdb");
con.Open();
Console.WriteLine("Current state is: " + con.State);
Console.WriteLine("Connection string is: "+con.ConnectionString );
Console.WriteLine("Datasource is: " + con.DataSource);
Console.WriteLine("Database is: " + con.Database );
Console.WriteLine("Provider is:"+con.Provider );
Console.WriteLine("Server Version is:"+con.ServerVersion );
con.Close();
Console.WriteLine("Now,Current state is: " + con.State);
Console.ReadLine();
}
}
}

35

Command With A Data Reader


Once you have defined your command we need to decided how you want to use it, the
simplest approach is to use a Data Reader, which allows you to quickly retrieve all your
results.
Data Reader uses a live connection and should be used quickly and then closed. The Data
Reader is also simple. It support forward only ,read only access to your results which is
generally all you need when retrieving in formation.
Because of the Data Readers option nature, it provide better performance than the data set.
Before you can use a Data Reader more sure you have to opened the connection.
To create a Data Reader you can use Execute Reader method of command object.
Oledb Data Reader rd = cmd.Execute Reader ();
Properties Of Oledb Data Reader Object
PROPERTY

DATA TYPE

Field Count

Int32

Is Closed

Boolean

Item

Object

Records Affected

Int32

DESCRIPTION
Indicates the depth of nesting for the current row
(read-only).
Indicates whether the Data Reader Is closed.(Read
only)
Returns the contents of the column for the currents
now (read-only)
Indicates the no. of records affected by the queries
submitted.(read-only)

Ass:12
36

Write a program to give an application of add,update,delete,display using console application


of Data Reader.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;
namespace ConsoleApplicationnnn
{
class Program
{
static void Main(string[] args)
{
bool flag = false;
string strcon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\\db1.mdb";
OleDbConnection con = new OleDbConnection(strcon);
con.Open();
Showins();
do
{
Console.WriteLine("Enter The Command: ");
string usercommand = Console.ReadLine();
switch (usercommand.ToUpper())
{
case "I":
Insnewrecord(con);
break;
case "U":
Updaterecord(con);
break;
case "D":
37

Deleterecord(con);
break;
case "L":
Listinfo(con);
break;
case "S":
Showins();
break;
case "Q":
flag = true;
break;
default:
Console.WriteLine("Invalid Choice...");
Console.WriteLine();
break;
}
}while (flag == false);
con.Close();
}
static void Showins()
{
Console.WriteLine();
Console.WriteLine("D : Delete an existing from info table");
Console.WriteLine("I : Insert a new record into info table");
Console.WriteLine("U : Update an existing record from info table");
Console.WriteLine("L : Displays current record info using datareader");
Console.WriteLine("S : Shows these options to user ");
Console.WriteLine("Q : for quite the programe");
}
static void Listinfo(OleDbConnection cn)
{
string str = "select * from book";
38

OleDbCommand cmd = new OleDbCommand(str, cn);


OleDbDataReader rd = cmd.ExecuteReader();
while (rd.Read())
{
Console.WriteLine("id: {0}, name: {1}, author: {2}, Price: {3}", rd["id"],rd["name"],
rd["author"], rd["price"]);
Console.WriteLine();
}
rd.Close();
}
static void Insnewrecord(OleDbConnection cn)
{
string str = "insert into book(id,name,author,price) values (@i,@nm,@a,@p)";
OleDbCommand cmd = new OleDbCommand(str, cn);
Console.WriteLine("ID: ");
cmd.Parameters.Add("@i", OleDbType.Integer).Value = Console.ReadLine();
Console.WriteLine("NAME: ");
cmd.Parameters.Add("@nm", OleDbType.VarChar).Value = Console.ReadLine();
Console.WriteLine("AUTHOR: ");
cmd.Parameters.Add("@a", OleDbType.VarChar).Value = Console.ReadLine();
Console.WriteLine("PRICE: ");
cmd.Parameters.Add("@p", OleDbType.Integer).Value = Console.ReadLine();
cmd.ExecuteNonQuery();
Console.WriteLine();
Console.WriteLine("Successfully Added..");
}
static void Deleterecord(OleDbConnection cn)
{
string str = "delete from book where id=@i";
OleDbCommand cmd=new OleDbCommand (str,cn);
Console.WriteLine();
Console.WriteLine("Enter thr ID that You want to delete: ");
cmd.Parameters.Add("@i",OleDbType.Integer).Value=Console.ReadLine();
39

cmd.ExecuteNonQuery();
}
static void Updaterecord(OleDbConnection cn)
{
string str = "update book set name=@nm,author=@a,price=@p where id=@i";
OleDbCommand cmd = new OleDbCommand(str, cn);
Console.WriteLine();
Console.WriteLine("NAME: ");
cmd.Parameters.Add("@nm", OleDbType.VarChar).Value =Console.ReadLine();
Console.WriteLine("AUTHOR: ");
cmd.Parameters.Add("@a", OleDbType.VarChar).Value = Console.ReadLine();
Console.WriteLine("PRICE: ");
cmd.Parameters.Add("@p", OleDbType.VarChar).Value = Console.ReadLine();
Console.WriteLine("Enter the id of record that you want to update: ");
cmd.Parameters.Add("@i", OleDbType.VarChar).Value = Console.ReadLine();
cmd.ExecuteNonQuery();
Console.WriteLine();
Console.WriteLine("Record Updated Successfully..");
}
}
}

40

Ass:13
Write a program to an application of add,update, delete, using windows application of
Data Reader .
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string strcon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\\ppm
programs\\db1.mdb";
OleDbConnection con=new OleDbConnection(strcon);
string str= "insert into book_info (book_id,book_name,author,price) values
(@bid,@bname,@bauthor,@bprice)";
OleDbCommand cmd = new OleDbCommand(str, con);
con.Open();
cmd.Parameters.Add("@bid", OleDbType.Integer).Value = textBox1.Text;
cmd.Parameters.Add("@bname", OleDbType.VarChar).Value = textBox2.Text;
cmd.Parameters.Add("@bauthor", OleDbType.VarChar).Value = textBox3.Text;
cmd.Parameters.Add("@bprice", OleDbType.Integer).Value = textBox4.Text;
41

cmd.ExecuteNonQuery();
con.Close();
}
private void button2_Click(object sender, EventArgs e)
{
string strcon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\\ppm
programs\\db1.mdb";
OleDbConnection con = new OleDbConnection(strcon);
string str = "update book_info set book_name=?, author=?, price=? where
book_id=?";
OleDbCommand cmd = new OleDbCommand(str, con);
con.Open();
cmd.Parameters.Add("@bname", OleDbType.VarChar).Value = textBox2.Text;
cmd.Parameters.Add("@bauthor", OleDbType.VarChar).Value = textBox3.Text;
cmd.Parameters.Add("@bprice", OleDbType.Integer).Value = textBox4.Text;
cmd.Parameters.Add("@bid", OleDbType.Integer).Value = textBox1.Text;
cmd.ExecuteNonQuery();
con.Close();
}
private void button3_Click(object sender, EventArgs e)
{
string strcon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\\ppm
programs\\db1.mdb";
OleDbConnection con = new OleDbConnection(strcon);
string str = "delete from book_info where book_id=@bid";
OleDbCommand cmd = new OleDbCommand(str, con);
con.Open();
cmd.Parameters.Add("@bid", OleDbType.Integer).Value = textBox1.Text;
//cmd.Parameters.Add("@bname", OleDbType.VarChar).Value = textBox2.Text;
//cmd.Parameters.Add("@bauthor", OleDbType.VarChar).Value = textBox3.Text;
//cmd.Parameters.Add("@bprice", OleDbType.Integer).Value = textBox4.Text;
cmd.ExecuteNonQuery();
con.Close();

} }
42

Data Adapter Object

It acts as a bridge between the connected and disconnected halves of the ADO.NET

object model. You can use a data adapter to pull data from your database in to your dataset.
The data adapter can also take the cached updates stored in the dataset and submit them to
your database.
For eg. You can create an SQL statement that select a set of rows, create a command
that represent it and use the data adapter object to automatically retrieve all the matching
values and insert them into dataset.
Every data Adapter can hold a reference to four different command on for each types of
application. You can set these commands through delete command, insert command, select
command & update command properties. When you want to store the result of the query in
an ADO.NET Data set object ? you could write code to populate a data set with new row by
looping through the data available in a data reader.

43

Properties of Data Adapter object :-

Property
Accept Changes
During Fill
Continue update
on Error

Data Type

Description
Determines the row state of the rows

Boolean

retrieved by the Data Adapter (default


=true)
Controls whether the Data Adapter will

Boolean

Delete Command

Oledb command

Insert command

Oledb command

Select command

Oledb command

Table Mappings
Update
Command

continue to submit changes if it


encounters an error (default=false)
Command used to submit pending
detletions
Command used to submit pending
insertions.
Command used to query data base and

Data Table

fetch results into a dataset or data table.


Collection of information the Data Adapter

Mapping

uses to map the results of the query to the

Collection

Data set.
Command used to submit pending

Oledb command

update.

44

Ass:14
Write a program to give an application of add, update, delete with windows application using
Data Adapter.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
OleDbConnection con = new
OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\\ppm
programs\\db1.mdb");
OleDbDataAdapter ad;
DataSet ds;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ds = new DataSet();
ad = new OleDbDataAdapter("select * from book_info", con);
ad.Fill(ds, "book_info");
DataRow r = ds.Tables["book_info"].NewRow();
r["book_id"] = Convert.ToInt32(textBox1.Text);
r["book_name"] = textBox2.Text;
45

r["author"] = textBox3.Text;
r["price"] = Convert.ToInt32(textBox4.Text);
ds.Tables["book_info"].Rows.Add(r);
string str = "insert into book_info(book_id,book_name,author,price) values
(@bid,@bname,@bauthor,@bprice)";
ad.InsertCommand = new OleDbCommand(str, con);
ad.InsertCommand.Parameters.Add("@bid", textBox1.Text);
ad.InsertCommand.Parameters.Add("@bname", textBox2.Text);
ad.InsertCommand.Parameters.Add("@bauthor", textBox3.Text);
ad.InsertCommand.Parameters.Add("@bprice", textBox4.Text);
ad.Update(ds, "book_info");
}
private void button2_Click(object sender, EventArgs e)
{
ds = new DataSet();
ad = new OleDbDataAdapter("select * from book_info where book_id=@bid", con);
ad.SelectCommand.Parameters.Add("@bid", textBox1.Text);
ad.Fill(ds, "book_info");
foreach(DataRow r in ds.Tables["book_info"].Rows)
{
if(r["book_id"].ToString()==textBox1.Text)
{
r[1] = textBox2.Text;
r[2] = textBox3.Text;
r[3] = textBox4.Text;
}
}
string str = "update book_info set
book_name=@bname,author=@bauthor,price=@bprice where book_id=@bid";
ad.UpdateCommand = new OleDbCommand(str, con);
ad.UpdateCommand.Parameters.AddWithValue("@bname", textBox2.Text);
ad.UpdateCommand.Parameters.AddWithValue("@bauthor", textBox3.Text);
ad.UpdateCommand.Parameters.AddWithValue("@bprice", textBox4.Text);
ad.UpdateCommand.Parameters.AddWithValue("@bid", textBox1.Text);
46

ad.Update(ds, "book_info");
}
private void button3_Click(object sender, EventArgs e)
{
ds = new DataSet();
ad = new OleDbDataAdapter("select * from book_info where book_id=@bid", con);
ad.SelectCommand.Parameters.Add("@bid", textBox1.Text);
ad.Fill(ds, "book_info");
foreach (DataRow r in ds.Tables["book_info"].Rows)
{
if (r["book_id"].ToString() == (textBox1.Text))
{
r.Delete();
}
}
string str = "delete from book_info where book_id=@bid";
ad.DeleteCommand = new OleDbCommand(str, con);
ad.DeleteCommand.Parameters.Add("@bid", textBox1.Text);
//ad.DeleteCommand.Parameters.Add("@bname", textBox2.Text);
//ad.DeleteCommand.Parameters.Add("@bauthor", textBox3.Text);
//ad.DeleteCommand.Parameters.Add("@bprice", textBox4.Text);
ad.Update(ds, "book_info");
}
}
}

47

Datatable object

The data Adapter stores the results of your query in a data table, an object similar to the

data row reader object.

Data Reader allow you to get results of the query quickly but offers little text functionality.

You cant modify the data in the data reader and that you cant move back to a previous

row.

You can modify, sort, and filter, the data in the data table feature not available through

data reader.

Along with this data table has columns property that returns a collection of data column

object. Each data column corresponds to a column in the results of your query.
Data Table
Data Row
Data column

A data table is a memory resident of database table in a dataset.

Data table properties :Property


Case sensitive
Columns
Minimum capacity
Primary key
Rows

Data type
Boolean
Data column

Description
Controls whether string
Contains the collection to data column

collection

objects for the datatable


Controls now much memory in row that

Integer

the datatable will reserve utility.


Array of data column Contains information about the primary
object
Data row collection

key for the data table


Contains the collection of data row
objects for the datatable..

48

Ass:15
Write a program to create a table dynamically using Data Table object.
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
namespace createtable
{
class Program
{
static void Main(string[] args)
{
DataTable dt = new DataTable("student");
DataColumn dsr = new DataColumn("srno", typeof(int));
dsr.AutoIncrement = true;
dsr.AutoIncrementSeed = 1;
dsr.AutoIncrementStep = 1;
dt.Columns.Add(dsr);
DataColumn dc = new DataColumn("stuid", typeof(int));
dt.Columns.Add(dc);
DataColumn dc1 = new DataColumn("stuname", typeof(string));
dc1.MaxLength = 5;
dt.Columns.Add(dc1);
DataColumn dc2 = new DataColumn("stuper", typeof(double));
dt.Columns.Add(dc2);
DataColumn[] pk = new DataColumn[1];
pk[0] = dt.Columns["stuid"];
dt.PrimaryKey = pk;
DataRow dr = dt.NewRow();
dr[1] = 11;
dr[2] = "aaa";
dr[3] = 23.23;
49

dt.Rows.Add(dr);
DataRow dr1 = dt.NewRow();
dr1[1] = 12;
dr1[2] = "bbb";
dr1[3] = 23.24;
dt.Rows.Add(dr1);
DataRow dr2 = dt.NewRow();
dr2["stuid"] = 13;
dr2["stuname"] = "ccc";
dr2[3] = 23.25;
dt.Rows.Add(dr2);
Console.WriteLine("........records of the table {0} is........", dt.TableName);
Console.WriteLine();
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn col in dt.Columns)
{
Console.WriteLine("{0} = {1}", col.ColumnName, row[col]);
}
Console.WriteLine();
}
Console.ReadLine();
}
}
}

Data set :50

Data set is a set of data. When developers decides to give the results returned by the

queries , they generally picture data in a grid, much are Microsoft Excel spreadsheet.
The Data reader which is fast, efficient structure that lets you retrieve the results of the
query. The Data Reader is built for speed because it supports very limited functionality. The
data in the Data Reader is read only and once you have morel on the read the next row,
theres no going back to reexamine previous results.
Features of Data set :1.
Working with disconnected Data.
The data in your Data set is disconnected from your database. Once you fetch the results of
a query into a Dataset and the your database. Changes you make to the contents of the
dataset will not affect your database for other users modify data in your database that
corresponds to the data in your dataset you will not see those changes in you dataset.
one benefit is that it does not required a live connection to your database.
2.
Scrolling , sorting , searching & filtering.
it lets you examine the contents of any row in your dataset at any time. You can loop back &
forth through the results of you query as often as you like.
Dataset objects also lets you change the way you new the results of queries. You can sort the
dataset based on a columns. You can search for a row of data based on simple search
criteria.
3.
Caching changes :It allows you to cache changes to a row of data so that you can submit changes to your
database using the data Adapter you can also examine modified rows in your dataset to
determine how the rows has charged inserted , modified or deleted ) as well as to compare
both the original & current values of for each row.

Creating a Data set:Dataset ds = new Dataset (Data set name );


Console.WriteLine ( ds . data set name);
Properties of Dataset :-

Property

Datatype

Datasetname

String

Description
Indicates the name of the
51

dataset
Haserrors

Boolean

Indicates whether the dataset


contains errors

Ass:16
Write to create table using Data Set and Data Adapter.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;
52

namespace dataadepter
{
class Program
{
static void Main(string[] args)
{
OleDbConnection con = new OleDbConnection
("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\\db1.mdb");
OleDbDataAdapter ad = new OleDbDataAdapter ("select * from info", con);
OleDbDataAdapter ad1 = new OleDbDataAdapter ("select * from customer", con);
DataSet ds = new DataSet();
ad.Fill(ds, "info");
ad1.Fill(ds, "customer");
foreach (DataTable dt in ds.Tables)
{
Console.WriteLine(" data of table {0} is ", dt.TableName);
foreach (DataRow dr1 in dt.Rows)
{
foreach (DataColumn dc1 in dt.Columns)
{
Console.WriteLine("{0} = {1}", dc1.ColumnName, dr1[dc1]);
}
}
Console.WriteLine();
}
Console.ReadLine();
}
}
}

53

54

Ass:17
Write a program to give application of first, next, previous, last on a given database.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
OleDbConnection con = new
OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\\ppm
programs\\db1.mdb");
OleDbDataAdapter ad;
DataSet ds;
DataRow r;
static int c = 0;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ad = new OleDbDataAdapter("select * from book_info", con);
ds = new DataSet();
ad.Fill(ds, "book_info");
c = 0;
r = ds.Tables["book_info"].Rows[c];
textBox1.Text = r["book_id"].ToString();
55

textBox2.Text = r["book_name"].ToString();
textBox3.Text = r["author"].ToString();
textBox4.Text = r["price"].ToString();
}
private void button2_Click(object sender, EventArgs e)
{
ad = new OleDbDataAdapter("select * from book_info", con);
ds = new DataSet();
ad.Fill(ds, "book_info");
int i=ds.Tables["book_info"].Rows.Count;
if(c<i-1)
{
c = c + 1;
r = ds.Tables["book_info"].Rows[c];
textBox1.Text = r["book_id"].ToString();
textBox2.Text = r["book_name"].ToString();
textBox3.Text = r["author"].ToString();
textBox4.Text = r["price"].ToString();
}
}
private void button3_Click(object sender, EventArgs e)
{
ad = new OleDbDataAdapter("select * from book_info", con);
ds = new DataSet();
ad.Fill(ds, "book_info");
if(c>0)
{
c = c - 1;
r = ds.Tables["book_info"].Rows[c];
textBox1.Text = r["book_id"].ToString();
textBox2.Text = r["book_name"].ToString();
textBox3.Text = r["author"].ToString();
textBox4.Text = r["price"].ToString();
}
56

}
private void button4_Click(object sender, EventArgs e)
{
ad = new OleDbDataAdapter("select * from book_info", con);
ds = new DataSet();
ad.Fill(ds, "book_info");
int i=ds.Tables["book_info"].Rows.Count;
c=i-1;
r = ds.Tables["book_info"].Rows[c];
textBox1.Text = r["book_id"].ToString();
textBox2.Text = r["book_name"].ToString();
textBox3.Text = r["author"].ToString();
textBox4.Text = r["price"].ToString();
}
}
}

Data view object :

The data table objects select method is power full & flexible, but its not always the best

solution. It has major two major limitations.It accepts dynamic search criteria , its not terribly
efficient.
The ado.net data table object is roughly equivalent to a table in a database so you might
assume that the data view object is similar to a view in a data base.
The data view object does not maintain its own copy of data. When you access data
through a data view, the data view returns data stored in the corresponding data table.

Creating data view objects :There are two ways to create a DataView. You can use the DataView constructor, or you can
create a reference to the DefaultView property of the DataTable. The DataView constructor
57

can be empty, or will also take either a DataTable as a single argument, or a DataTable along
with filter criteria, sort criteria, and a row state filter. For more information about the additional
arguments available for use with the DataView, see Sorting and Filtering Data Using a
DataView.
Because the index for a DataView is built both when the DataView is created, and when any
of the Sort, RowFilter, or RowStateFilter properties are modified, you will achieve best
performance by supplying any initial sort order or filtering criteria as constructor arguments
when you create the DataView. Creating a DataView without specifying sort or filter criteria
and then setting the Sort, RowFilter, or RowStateFilter properties later results in the index
being built at least twice: once when the DataView is created, and again when any of the sort
or filter properties are modified.
Note that if you create a DataView using the constructor that does not take any arguments,
you will not be able to use the DataView until you have set the Table property.

58

Ass : 18
Write a program to create a Data View application.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;
namespace dataview_app
{
class Program
{
static void Main(string[] args)
{
string strcon="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\\db1.mdb";
string sql = "select * from book";
OleDbDataAdapter da=new OleDbDataAdapter(sql,strcon );
DataTable tbl = new DataTable("abc");
da.Fill(tbl);
DataView vw = new DataView(tbl);
vw.Sort = "name";
for (int i = 0; i < vw.Count; i++)
{
Console.WriteLine();
Console.Write("ID: " + vw[i]["id"].ToString() + " , ");
Console.Write("NAME :" + vw[i]["name"].ToString() + " , ");
Console.Write("AUTHOR: " + vw[i]["author"].ToString() + " , ");
Console.Write("PRICE: " + vw[i]["price"].ToString() + " , ");
}
Console.ReadLine();
}

}}
59

Ass : 19
Write a program to create a console application of add, update , delete, display using console
application using Data Adapter.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;
using System.Data;
namespace ConsoleApplication_DA
{
class Program
{
static string strcon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\\db1.mdb";
static OleDbConnection con = new OleDbConnection(strcon);
static OleDbDataAdapter ad=new OleDbDataAdapter ("select * from book",con);
static DataSet ds = new DataSet();
static void Main(string[] args)
{
bool flag = false;
ad.Fill(ds, "book");
DataColumn[] dc = new DataColumn[1];
dc[0] = ds.Tables["book"].Columns["id"];
ds.Tables["book"].PrimaryKey = dc;
string usercommand = "";
Showins();
do
{
Console.WriteLine("please enter your command");
60

usercommand = Console.ReadLine();
switch (usercommand.ToUpper())
{
case "I":
Insnewrecord(con);
break;
case "U":
Updaterecord(con);
break;
case "D":
Deleterecord(con);
break;
case "L":
Listinfo(con);
break;
case "S":
Showins();
break;
case "Q":
flag = true;
break;
default:
Console.WriteLine("invalid choice");
Console.WriteLine();
break;
}
} while (flag == false);
}
static void Showins()
{
Console.WriteLine();
Console.WriteLine("D : Delete an existing from info table");
Console.WriteLine("I : Insert a new record into info table");
61

Console.WriteLine("U : Update an existing record from info table");


Console.WriteLine("L : Displays current record info using datareader");
Console.WriteLine("S : Shows these options to user ");
Console.WriteLine("Q : for quite the programe");
}
static void Deleterecord(OleDbConnection cn)
{
ad.DeleteCommand = new OleDbCommand("delete from book where id=@i",cn);
Console.WriteLine("Enter the ID that you want to Delete: ");
string a = Console.ReadLine();
ad.DeleteCommand.Parameters.Add("@i", OleDbType.Integer).Value = a;
DataRow dr = ds.Tables["book"].Rows.Find(a);
dr.Delete();
ad.Update(ds, "book");
Console.WriteLine();
Console.WriteLine("Record Deleted Successfully");
}
static void Updaterecord(OleDbConnection cn)
{
ad.UpdateCommand = new OleDbCommand("update book set
name=@nm,author=@au,price=@p where id=@i",cn);

Console.WriteLine("Name: ");
string a = Console.ReadLine();
ad.UpdateCommand.Parameters.Add("@nm", OleDbType.VarChar ).Value = a;
Console.WriteLine("Author: ");
string b = Console.ReadLine();
ad.UpdateCommand.Parameters.Add("@au", OleDbType.VarChar).Value = b;
Console.WriteLine("Price: ");
62

string c = Console.ReadLine();
ad.UpdateCommand.Parameters.Add("@p", OleDbType.VarChar).Value = c;
Console.WriteLine("Enter the ID of the record to be updated: ");
string d = Console.ReadLine();
ad.UpdateCommand.Parameters.Add("@i", OleDbType.VarChar).Value = d;
DataRow dr = ds.Tables["book"].Rows.Find(d);
int index = ds.Tables["book"].Rows.IndexOf(dr);
ds.Tables["book"].Rows[index]["name"] = a;
// ad.Update(ds, "book");
ds.Tables["book"].Rows[index]["author"] = b;
// ad.Update(ds, "book");
ds.Tables["book"].Rows[index]["price"] = c;
ad.Update(ds, "book");
Console.WriteLine();
Console.WriteLine("Record UPdated Successfully");
}
static void Insnewrecord(OleDbConnection cn)
{
ad.InsertCommand = new OleDbCommand("insert into
book(id,name,author,price) values (@i,@nm,@a,@p)", cn);
Console.WriteLine("ID: ");
string a = Console.ReadLine();
ad.InsertCommand.Parameters.Add("@i",OleDbType.VarChar).Value = a;
Console.WriteLine("Name: ");
string b = Console.ReadLine();
ad.InsertCommand.Parameters.Add("@nm", OleDbType.VarChar).Value = b;
Console.WriteLine("Author: ");
string c = Console.ReadLine();
ad.InsertCommand.Parameters.Add("@a", OleDbType.VarChar).Value = c;
Console.WriteLine("Price: ");
string d = Console.ReadLine();
63

ad.InsertCommand.Parameters.Add("@p", OleDbType.VarChar).Value = d;
DataRow dr = ds.Tables["book"].NewRow();
dr["id"] = a;
dr["name"] = b;
dr["author"] = c;
dr["price"] = d;
ds.Tables["book"].Rows.Add(dr);
ad.Update(ds, "book");
Console.WriteLine();
Console.WriteLine("Record add succsfully");
}
static void Listinfo(OleDbConnection cn)
{
ad.Fill(ds, "book");
for (int i = 0; i < ds.Tables["book"].Rows.Count; i++)
{
Console.WriteLine();
Console.Write("ID: " + ds.Tables["book"].Rows[i]["id"].ToString() + " , ");
Console.Write("NAME: " + ds.Tables["book"].Rows[i]["name"].ToString()+" , ");
Console.Write("AUTHOR: " + ds.Tables["book"].Rows[i]["author"].ToString()+" ,
");
Console.Write("PRICE: " + ds.Tables["book"].Rows[i]["price"].ToString()+" , ");
}
}
}
}

64

You might also like