C# Manual
C# Manual
Laboratory Manual
PROGRAMMING IN C#.NET
For
ad
FOREWORD
It is my great pleasure to present this laboratory manual for Third year engineering students
for the subject of Programming in C#.NET
As a student, many of you may be wondering with some of the questions in your mind
regarding the subject and exactly what has been tried is to answer through this manual.
As you may be aware that MGM has already been awarded with ISO 9001:2000
certification and it is our endure to technically equip our students taking the advantage of
the procedural aspects of ISO 9001:2000 Certification.
Faculty members are also advised that covering these aspects in initial stage itself, will
greatly relived them in future as much of the load will be taken care by the enthusiasm
energies of the students once they are conceptually clear.
Dr. S.D.Deshmukh
Principal
LABORATORY MANUAL CONTENTS
This manual is intended for the Third year students of Computer Science and Engineering
in the subject of Programming in C# .NET. This manual typically contains practical/Lab
Sessions related Programming In C# .NET covering various aspects related the subject to
enhanced understanding.
Students are advised to thoroughly go through this manual rather than only topics
mentioned in the syllabus as practical aspects are the key to understanding and conceptual
visualization of theoretical aspects covered in the books.
Dr.V.B.Musande Ms L.N.Jadhav
HOD, CSE Lecturer, CSE Dept.
MGM’s
II. Preparing graduates for higher education and research in computer science and engineering
enabling them to develop systems for society development.
III. To exhibit professionalism, communication skills and adapt to current trends by engaging in
lifelong learning.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities
with an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to
the professional engineering practice.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms
of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
SUBJECT INDEX
Part-I Console Application
1. Make entry in the Log Book as soon as you enter the Laboratory.
2. All the students should sit according to their roll numbers starting from their left to
right.
3. All the students are supposed to enter the terminal number in the log book.
5. All the students are expected to get at least the algorithm of the program/concept
to be implemented.
1. Submission related to whatever lab work has been completed should be done during the
next lab session. The immediate arrangements for printouts related to submission on the
day of practical assignments.
2. Students should be taught for taking the printouts under the observation of lab teacher.
EXPERIMENT No. 1
AIM - Introduction to Dotnet Framework
Objectives:
To understand the concept and need on .Net framework.
To understand the components of .Net framework.
.Ability to install visual studio 2010.
Theory:
POINTS TO BE COVERED
- What is Dotnet?
- Advantages of Dotnet
- Dotnet languages
.net (network) is a generic top-level domain (gTLD) used on the Internet's Domain Name
System. The Microsoft .NET Framework is a software framework that can be installed on
computers running Microsoft Windows operating systems. It includes a large library of
coded solutions to common programming problems and a virtual machine that manages
the execution of programs written specifically for the framework.
The framework's Base Class Library provides a large range of features including user
interface, data and data acces, database connectivity, cryptography, web application
development, numeric algorithms, and network communications. The class library is used
by programmers, who combine it with their own code to produce applications.Programs
written for the .NET Framework execute in a software environment that manages the
program's runtime requirements. Also part of the .NET Framework, this runtime
environment is known as the Common Language Runtime (CLR). The CLR provides the
appearance of an application virtual machine so that programmers need not consider the
capabilities of the specific CPU that will execute the program. The CLR also provides other
important services such as security, memory management, and exception handling. The
class library and the CLR together constitute the .NET Framework.
Theory:
Decision making structures require that the programmer specify one or more conditions to
be evaluated or tested by the program, along with a statement or statements to be
executed if the condition is determined to be true, and optionally, other statements to be
executed if the condition is determined to be false.
Following is the general from of a typical decision making structure found in most of the
programming languages:
If else statement
An if statement can be followed by an optional else statement, which executes when the
boolean expression is false.
Syntax:
The syntax of an if...else statement in C# is:
if(boolean_expression)
{
/* statement(s) will execute if the boolean expression is true */
}
else
{
/* statement(s) will execute if the boolean expression is false */
}
If the boolean expression evaluates to true, then the if block of code will be executed,
otherwise else block of code will be executed.
Flow Diagram:
Example:
using System;
namespace DecisionMaking
{
class Program
{
static void Main(string[] args)
{
When the above code is compiled and executed, it produces the following result:
Nested If-else:
It is always legal in C# to nest if-else statements, which means you can use one if or else if
statement inside another if or else if statement(s).
Syntax:
The syntax for a nested if statement is as follows:
if( boolean_expression 1)
{
/* Executes when the boolean expression 1 is true */
if(boolean_expression 2)
{
/* Executes when the boolean expression 2 is true */
}
}
Switch Statement
A switch statement allows a variable to be tested for equality against a list of values. Each
value is called a case, and the variable being switched on is checked for each switch
case.
Syntax:
The syntax for a switch statement in C# is as follows:
switch(expression){
case constant-expression :
statement(s);
break; /* optional */
case constant-expression :
statement(s);
break; /* optional */
Flow Diagram:
Loops
There may be a situation, when you need to execute a block of code several number of
times. In general statements are executed sequentially: The first statement in a function is
executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated
execution paths.
Here, key point of the while loop is that the loop might not ever run. When the condition is
tested and the result is false, the loop body will be skipped and the first statement after the
while loop will be executed.
For loop
Executes a sequence of statements multiple times and abbreviates the code that manages
the loop variable.
A for loop is a repetition control structure that allows you to efficiently write a loop that
needs to execute a specific number of times.
Syntax:
The syntax of a for loop in C# is:
for ( init; condition; increment )
{
statement(s);
}
Here is the flow of control in a for loop:
The init step is executed first, and only once. This step allows you to declare and
initialize any loop control variables. You are not required to put a statement here, as
long as a semicolon appears.
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is
false, the body of the loop does not execute and flow of control jumps to the next
statement just after the for loop.
After the body of the for loop executes, the flow of control jumps back up to
the incrementstatement. This statement allows you to update any loop control
variables. This statement can be left blank, as long as a semicolon appears after the
condition.
The condition is now evaluated again. If it is true, the loop executes and the process
repeats itself (body of loop, then increment step, and then again condition). After the
condition becomes false, the for loop terminates.
do...while loop
Unlike for and while loops, which test the loop condition at the top of the loop,
the do...while loop checks its condition at the bottom of the loop.
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to
execute at least one time.
Syntax:
The syntax of a do...while loop in C# is:
do
{
statement(s);
}while( condition );
Notice that the conditional expression appears at the end of the loop, so the statement(s) in
the loop execute once before the condition is tested.
If the condition is true, the flow of control jumps back up to do, and the statement(s) in the
loop execute again. This process repeats until the given condition becomes false.
C# allows to use one loop inside another loop. Following section shows few examples to
illustrate the concept.
Syntax:
The syntax for a nested for loop statement in C# is as follows:
for ( init; condition; increment )
{
for ( init; condition; increment )
{
statement(s);
}
statement(s);
}
The syntax for a nested while loop statement in C# is as follows:
while(condition)
{
while(condition)
{
statement(s);
}
statement(s);
}
The syntax for a nested do...while loop statement in C# is as follows:
do
{
statement(s);
do
{
statement(s);
}while( condition );
}while( condition );
Foreach loop
syntax:
foreach (string name in arr)
{
Where, name is a string variable that takes value from collection as arr and
then processes them in the body area.
using System;
namespace foreach_loop
{
class Program
{
static void Main(string[] args)
{
string[] arr = new string[5]; // declari ng array
Output
Hello Steven
Hello Clark
Hello Mark
Hello Thompson
Hello John
Questions:
1.write a program to perform arithematic operaton in console application using switch case.
2. write a program to perform reverse number.
3. write a program to perform laep year and fabonic series.
4. write a program to check whether the given No.is armstong number or not.
5.
Objectives:
To understand the concept and declaration of member of class.
To understand the concept of properties.
Class Definition
A class definition starts with the keyword class followed by the class name; and the class
body, enclosed by a pair of curly braces. Following is the general form of a class definition:
Access specifiers specify the access rules for the members as well as the class itself, if
not mentioned then the default access specifier for a class type is internal. Default
access for the members is private.
Data type specifies the type of variable, and return type specifies the data type of the
data, the method returns, if any.
To access the class members, you will use the dot (.) operator.
The dot operator links the name of an object with the name of a member.
A member function of a class is a function that has its definition or its prototype within the
class definition like any other variable. It operates on any object of the class of which it is a
member, and has access to all the members of a class for that object.
Member variables are attributes of an object (from design perspective) and they are kept
private to implement encapsulation. These variables can only be accessed using the public
member functions.
Object:
Object is a run time entity.We used the object to access the member and the functionof
class.An object is created in the memory using the keyword ‘new’.
Synax:
Properties enable a class to expose a public way of getting and setting values, while
hiding implementation or verification code.
A get property accessor is used to return the property value, and a set accessor is
used to assign a new value. These accessors can have different access levels. For
more information, see Restricting Accessor Accessibility (C# Programming Guide).
The value keyword is used to define the value being assigned by the set accessor.
Properties that do not implement a set accessor are read only.
Syntax:
<access specifier>datatype<name of property>
{
Get
{
//some optional statement
return<some private field>
}
Set
{
//some optional statement
<some private field>=value;
}
}
Example
class TimePeriod
{
private double seconds;
class Program
{
static void Main()
{
TimePeriod t = new TimePeriod();
Output
Time in hours: 24
Questions:
1. Write a console application for bank account in C# .Net.
2. Write a console application to display student information using class and object.
3. Write a console application to display employee information using properties.
4.Write a console application for a class person having data members name & age.Accept
the value for this using constructor.And display the output for one object.
5. Write a console application containing a method that will swap the value of two integer
type variable.
Objectives:
To understand the concept of Inheritance.
To understand the difference between class and abstract class
Theory:
What is Inheritance in C#
When a new class needs same members as an existing class, then instead of creating
those members again in new class, the new class can be created from existing class, which
is called as inheritance.
During inheritance, the class that is inherited is called as base class and the
class that does the inheritance is called as derived class and every non private
member in base class will become the member of derived class.
If you want the base class members to be accessed by derived class only , you
can apply access modifier Protected to the base class member.
Syntax
[Access Modifier] class ClassName : baseclassname
1. Single Inheritance
2. Hierarchical Inheritance
3. Multi Level Inheritance
4. Hybrid Inheritance
5. Multiple Inheritance
1.Single Inheritance
when a single derived class is created from a single base class then the
inheritance is called as single inheritance.
2. Hierarchical Inheritance
when more than one derived class are created from a single base class, then
that inheritance is called as hierarchical inheritance.
3. Multi Level Inheritance
when a derived class is created from another derived class, then that
inheritance is called as multi level inheritance.
4. Hybrid Inheritance
Any combination of single, hiera rchical and multi level inheritances is called as
hybrid inheritance.
5. Multiple Inheritance
when a derived class is created from more than one base class then that
inheritance is called as multiple inheritance. But multiple inheritance is not
supported by .net using classes and can be done using interfaces.
Handling the complexity that causes due to multiple inheritance is very complex.
Hence it was not supported in dotnet with class and it can be done with
interfaces.
Abstract class
Abstract classes are one of the essential behaviors provided by .NET. Commonly, you
would like to make classes that only represent base classes, and don’t want anyone to
create objects of these class types. You can make use ofabstract classes to implement
such functionality in C# using the modifier 'abstract'.
An abstract class means that, no object of this class can be instantiated, but can make
derivations of this.
Also, note that an abstract class does not mean that it should contain abstract members.
Even we can have anabstract class only with non abstract members. For example:
{
public void NonAbstractMethod()
{
Console.WriteLine("NonAbstract Method");
}
}
using System;
namespace abstractSample
{
//Creating an Abstract Class
abstract class absClass
{
//A Non abstract method
public int AddTwoNumbers(int Num1, int Num2)
{
return Num1 + Num2;
}
Output:
Added:30 multiplied:200
Questions:
1. Write a console application calculate the area and circumference of circle &rectangle
using inheritance .
2. Write a program for calculates the area and circumference of circle &rectangle using
abstract class.
3. Implement the concept of overloading in console application.
4. Implement the concept of folloeing inheritance
Student
Engg Student
Objectives:
To understand the concept of interface.
To understand the concept of Exception handling
Theory:
Interface:
Ex:
interface abc
{
void xyz();
}
In Demo :: xyz
In Sample :: xyz
Exception Handling :
Exceptions provide a way to transfer control from one part of a program to another. C#
exception handling is built upon four keywords: try, catch, finally and throw.
try: A try block identifies a block of code for which particular exceptions will be
activated. It's followed by one or more catch blocks.
catch: A program catches an exception with an exception handler at the place in a
program where you want to handle the problem. The catch keyword indicates the
catching of an exception.
finally: The finally block is used to execute a given set of statements, whether an
exception is thrown or not thrown. For example, if you open a file, it must be closed
whether an exception is raised or not.
throw: A program throws an exception when a problem shows up. This is done
using a throw keyword.
Syntax
Assuming a block will raise and exception, a method catches an exception using a
combination of the try and catch keywords. A try/catch block is placed around the code that
might generate an exception. Code within a try/catch block is referred to as protected code,
and the syntax for using try/catch looks like the following:
try
{
// statements causing exception
}
catch( ExceptionName e1 )
{
// error handling code
}
catch( ExceptionName e2 )
{
// error handling code
}
catch( ExceptionName eN )
{
// error handling code
}
finally
{
// statements to be executed
}
You can list down multiple catch statements to catch different type of exceptions in case
your try block raises more than one exception in different situations.
Exception Classes in C#
C# exceptions are represented by classes. The exception classes in C# are mainly directly
or indirectly derived from the System.Exception class. Some of the exception classes
derived from the System.Exception class are
the System.ApplicationException and System.SystemException classes
The following table provides some of the predefined exception classes derived from the
Sytem.SystemException class:
Handling Exceptions
C# provides a structured solution to the exception handling problems in the form of try and
catch blocks. Using these blocks the core program statements are separated from the
error-handling statements.
These error handling blocks are implemented using the try, catch and finally keywords.
Following is an example of throwing an exception when dividing by zero condition occurs:
using System;
namespace ErrorHandlingApplication
{
class DivNumbers
{
int result;
DivNumbers()
{
result = 0;
}
public void division(int num1, int num2)
{
try
{
result = num1 / num2;
}
catch (DivideByZeroException e)
{
Console.WriteLine("Exception caught: {0}", e);
}
finally
{
Console.WriteLine("Result: {0}", result);
} }
static void Main(string[] args)
{
DivNumbers d = new DivNumbers();
d.division(25, 0);
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result:
Questions.
1.
2
3
4
EXPERIMENT No. 6
AIM - Design a Logon form and validate it.
Objectives:
To understand the cocept all windows form controls.
Ability to write a program for windows application.
Theory:
- Create a logon form
- Enter the fields for username and password
- Validate whether the entered fields are correct or not.
- In Visual Studio, select File|New|Project. Visual studio will display the new project dialog
box.
- In the new project dialog box, click the windows Application icon. In the name field, type
a project name that describes the program you are binding, such as Demo program.
Then, in the location field, type the name of the folder in which you want visual studio to
place the projects folder and files. Click ok. Visual studio will display a design window
where you can drag and drop controls onto your form.
- To display the toolbox that contains the control you can drag and drop on to your form,
select View|Toolbox.Visual studio will open the Toolbox window.
- In the toolbox window, locate the various button control, textbox control and label
control
- In the property window give the text to the button, label and button control.
- Set the password char property for password textbox as “ * ”
- To run the programme select the debug menu and then press start.
- Your output must look as shown.
OUTPUT:
Conclusion:
Hence we have studied and implemented the logon form and how to validate
the values.
EXPERIMENT No7.
- +, _, *, /,log, sqr, cube, sqrt, cube root, mod, %, sin, cos, tan, cancel, 1/x, pie
Steps to create windows application
- In Visual Studio, select File|New|Project. Visual studio will display the new project dialog
box.
- In the new project dialog box, click the windows Application icon. In the name field, type
a project name that describes the program you are binding, such as Demo program.
Then, in the location field, type the name of the folder in which you want visual studio to
place the projects folder and files. Click ok. Visual studio will display a design window
where you can drag and drop controls onto your form.
- To display the toolbox that contains the control you can drag and drop on to your form,
select View|Toolbox.Visual studio will open the Toolbox window.
- In the toolbox window, locate the various button control and textbox control
- In the property window give the text to the button control
- As mentioned above the calculator must possess the buttons
- Use operators and select case statements to execute the programme.
- To run the programme select the debug menu and then press start.
Output:
Steps to create traffic signal windows application
- In Visual Studio, select File|New|Project. Visual studio will display the new project dialog
box.
- In the new project dialog box, click the windows Application icon. In the name field, type
a project name that describes the program you are binding, such as Demo program.
Then, in the location field, type the name of the folder in which you want visual studio to
place the projects folder and files. Click ok. Visual studio will display a design window
where you can drag and drop controls onto your form.
- To display the toolbox that contains the control you can drag and drop on to your form,
select View|Toolbox.Visual studio will open the Toolbox window.
- Design the Diagram of Square with signals on each terminals
- In the property window set the textbox property backcolor using colors red,blue and
green as the colors of the signal
- Drag and drop the timer control. Set the properties enable to true and set i nterval.
- To run the programme select the debug menu and then press start.
- Your output must look as shown.
- Output:
Conclusion:
Hence we have implemented the calculator programme and traffic
signal in C#.net.
EXPERIMENT No.8
Objectives:
To understand the concept of ADO .Net.
To understand the difference between Data Provider and Dataset.
Ablity to write a program for DataBase connectivity.
Theory:
- Explain block diagram
- Describe various components
- Write all the steps to connect to a database.
ADO.NET provides consistent access to data sources such as Microsoft SQL Server, as
well as data sources exposed through OLE DB and XML. Data-sharing consumer
applications can use ADO.NET to connect to these data sources and retrieve, manipulate,
and update data.
ADO.NET cleanly factors data access from data manipulation into discrete components
that can be used separately or in tandem. ADO.NET includes .NET Framework data
providers for connecting to a database, executing commands, and retrieving results. Those
results are either processed directly, or placed in an ADO.NET Dataset object in order to
be exposed to the user in an ad-hoc manner, combined with data from multiple sources, or
remote between tiers. The ADO.NET Dataset object can also be used independently of a
.NET Framework data provider to manage data local to the application or sourced from
XML.
The ADO.NET classes are found in System.Data.dll, and are integrated with the XML
classes found in System.Xml.dll. When compiling code that uses the System. Data
namespace, reference both System.Data.dll and System.Xml.dll. For an example of
compiling an ADO.NET application using a command line compiler
most applications need data access at one point of time making it a crucial component
when working with applications. Data access is making the application interact with a
database, where all the data is stored. Different applications have different requirements for
database access. C# .NET uses ADO .NET (Active X Data Object) as it's data access and
manipulation protocol which also enables us to work with data on the Internet. Let's take a
look why ADO .NET came into picture replacing ADO.
Block Diagram
Data Provider
The Data Provider is responsible for providing and maintaining the connection to the
database. A DataProvider is a set of related components that work together to provide data
in an efficient and performance driven manner. The .NET Framework currently comes with
two DataProviders: the SQL Data Provider which is designed only to work with Microsoft's
SQL Server 7.0 or later and the OleDb DataProvider which allows us to connect to other
types of databases like Access and Oracle. Each DataProvider consists of the following
component classes:
The DataReader object which provides a forward-only, read only, connected record set
The Data Adapter object which populates a disconnected Dataset with data and performs
update
A connection object establishes the connection for the application with the database. The
command object provides direct execution of the command to the database. If the
command returns more than a single value, the command object returns a DataReader to
provide the data. Alternatively, the DataAdapter can be used to fill the Dataset object. The
database can be updated using the command object or the DataAdapter.
ExecuteNonQuery:
Executes commands that have no return values such as INSERT, UPDATE or DELETE
ExecuteScalar: Returns a single value from a database query
ExecuteReader: Returns a result set by way of a DataReader object
The DataAdapter is the class at the core of ADO .NET's disconnected data access. It is
essentially the middleman facilitating all communication between the database and a
DataSet. The DataAdapter is used either to fill a DataTable or DataSet with data from the
database with it's Fill method. After the memory-resident data has been manipulated, the
DataAdapter can commit the changes to the database by calling the Update method. The
DataAdapter provides four properties that represent database commands:
SelectCommand
InsertCommand
DeleteCommand
UpdateCommand
When the Update method is called, changes in the DataSet are copied back to the
database and the appropriate InsertCommand, DeleteCommand, or UpdateCommand is
executed.
Sample Code
Using System.Data.OleDB
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
OleDbConnection con;
DataSet ds1;
OleDbDataAdapter da;
private void Form1_Load(object sender, EventArgs e)
{
con = new.OleDbConnection();
ds1 = new DataSet();
con.ConnectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=D:/MyWorkers1.mdb";
con.Open();
da.Fill(ds1, "MyWorkers1");
datagrid1.Datasource=ds1;
datagrid1.datamember=" MyWorkers1";
con.close();
}
private void btninsert_Click(object sender, EventArgs e)
{
con = new.OleDbConnection(="Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=D:/MyWorkers1.mdb");
con.Open();
icount=cmd.ExecuteNonQuery();
messagebox.show("row inserted");
con.close();
Updating Records
con = new.OleDbConnection(="Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=D:/MyWorkers1.mdb");
con.Open();
cmd=new Oledbcommand(str,con);
icount=cmd.ExecuteNonQuery();
messagebox.show("row updated");
con.close();
Questions:
Design a windows application to display the teacher information to perform select
and insert operation using oracle 10g database connections.
Design a windows application to display the student information to perform select
and update operation using MS-access database connections.
EXPERIMENT No.8
1. RequiredFieldValidator
2. RangeValidator
3. CompareValidator
4. RegularExpressionValidator
5. CustomValidator
6. ValidationSummary
The validation control classes inherit from the BaseValidator class and inherit its properties
and methods. Therefore, it would help to take a look at the properties and the methods of
this base class, which are common for all the validation controls:
Members Description
ControlToValidate Indicates the input control to validate.
Display Indicates how the error message is shown.
EnableClientScript Indicates whether client side validation will take.
Enabled Enables or disables the validator.
ErrorMessage Error string.
Text Error text to be shown if validation fails.
IsValid Indicates whether the value of the control is valid.
SetFocusOnError It indicates whether in case of an invalid control, the focus
should switch to the related input control.
ValidationGroup The logical group of multiple validators, where this control
belongs.
Validate() This method revalidates the control and updates the IsValid
property.
The RequiredFieldValidator:
The RequiredFieldValidator control ensures that the required field is not empty. It is
generally tied to a text box to force input into the text box.
<asp:RequiredFieldValidator ID="rfvcandidate"
runat="server" ControlToValidate ="ddlcandidate"
ErrorMessage="Please choose a candidate"
InitialValue="Please choose a candidate">
</asp:RequiredFieldValidator>
The RangeValidator:
The RangeValidator control verifies that the input value falls within a predetermined range.
Properties Description
Type it defines the type of the data; the available values are:
Currency, Date, Double, Integer and String
MinimumValue it specifies the minimum value of the range
MaximumValue it specifies the maximum value of the range
<asp:RangeValidator ID="rvclass"
runat="server"
ControlToValidate="txtclass"
ErrorMessage="Enter your class (6 - 12)"
MaximumValue="12"
MinimumValue="6" Type="Integer">
</asp:RangeValidator>
The CompareValidator:
The CompareValidator control compares a value in one control with a fixed value, or, a
value in another control.
Properties Description
Type it specifies the data type
ControlToCompare it specifies the value of the input control to compare with
ValueToCompare it specifies the constant value to compare with
Operator it specifies the comparison operator, the available values are:
Equal, NotEqual, GreaterThan, GreaterThanEqual, LessThan,
LessThanEqual and DataTypeCheck
<asp:CompareValidator ID="CompareValidator1"
runat="server"
ErrorMessage="CompareValidator">
</asp:CompareValidator>
The RegularExpressionValidator
The following table summarizes the commonly used syntax constructs for regular
expressions:
Apart from single character match, a class of characters could be specified that can be
matched, called the metacharacters.
Metacharacters Description
. Matches any character except \n
[abcd] Matches any character in the set
[^abcd] Excludes any character in the set
[2-7a-mA-M] Matches any character specified in the range
\w Matches any alphanumeric character and underscore
\W Matches any non-word character
\s Matches whitespace characters like, space, tab, new line etc.
\S Matches any non-whitespace character
\d Matches any decimal character
\D Matches any non-decimal character
Quantifier Description
* Zero or more matches
+ One or more matches
? Zero or one matches
{N} N matches
{N,} N or more matches
{N,M} Between N and M matches
The CustomValidator:
The CustomValidator control allows writing application specific custom validation routines
for both the client side and the server side validation.
The server side validation routine must be called from the control.s ServerValidate event
handler. The server side validation routine should be written in any .Net language, like C#
or C# .Net.
<asp:CustomValidator ID="CustomValidator1"
runat="server"
ClientValidationFunction=.cvf_func.
ErrorMessage="CustomValidator">
</asp:CustomValidator>
The ValidationSummary control does not perform any validation but shows a summary of
all errors in the page. The summary displays the values of the ErrorMessage property of all
validation controls that failed validation.
The following two mutually inclusive properties list out the error message:
<asp:ValidationSummary ID="ValidationSummary1"
runat="server"
DisplayMode = "BulletList"
ShowSummary = "true"
HeaderText="Errors:" />
Validation Groups:
Complex pages have different groups of information provided in different panels. In such a
situation a need for performing validation separately for separate group, might arise. This
kind of situation is handled using validation groups.
To create a validation group, you should put the input controls and the validation controls
into the same logical group by setting their ValidationGroup property.
Example:
The following example describes a form to be filled up by all the students of a school,
divided into four houses, for electing the school president. We will be using the validation
controls to validate the user input.
Questions:
Design a sign Up form & validate user phone no with exactly 10 digit and email-id.
Design a sign up form & validate username (minimum 8 characters &maximum 15
and only character) password and retype password (both should be same)
Design a web application form having loan amount,interest rate and duration
fields.calculate the simple interest and perform nacessary validation ie
o Ensures data has been entered for each field.
o Checking for non numeric value.
Objectives:
To understand the concept of master page.
Ability to create website using master page.
Theory:
For instance, if you would like to display a standard header and footer in each page of your
website, then you can generate the standard header and footer in a Master Page. That’s
how powerful a master page is to handle multiple forms and is easier to maintain
throughout what the website looks like. Take note, the ID attribute uniquely identifies the
placeholder, allowing you to put more than one placeholder in a master page.
To start - open your Visual Studio 2010, File and choose New Web Site, choose C#.
Choose ASP.NET Empty Web Site. Make the default File System; you can change the file
directory of your file. Just simply browse and name your folder where your file is being
saved and click Ok.
When we notice there’s no display, what are we going to do. We are going to Add
a Master Page. To do that, in your solution explorer, right click the name of your website
and choose Add new item. Choose MasterPage.master, the default name is MasterPage.
Make sure that the check box is checked, only place code in a separate file, not a
selectmaster page.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
Under the code, either you can choose Source, Split, and design. In order to show only the
code, use the design just like above, split shows both source and design and design shows
only a design.
Now, we are going to use design in order to see the full design of our Master Page. Click
design; first delete the current placeholder because we are going to create a new one.
In toolbox, choose Hyperlink and drag in your Page. Make 3 copies and name them Home,
About, and Settings.
So, this is how your Master Page looks like. In order to make multiple Web Forms, in your
Solution Explorer, click your web site name, right click and Add new item. Choose C# and
click Web Form. The default name is default, change it to Home to make it more
meaningful. Remember; make sure to check the select master page and Add. When you
notice another dialog box appears, it does mean that you are in the Master Page control.
Click MasterPage.master, then Ok.
Do the same procedure like what you created in the Home web form and name it About
and Setting. Now you’ve already created 3 Web Forms.
Back to the Master Page, drag Content PlaceHolder from your toolbox in
your Master Page.
Gdf
Click Home menu hyperlinks, in your properties setting, locate Navigate URL, click … and
choose Home Web Form that corresponds to your menu. Do the same procedure when
you link About and Settings Menu.
In Solution Explorer, double click Home Web Form. When you notice your cursor,
only ContentPlaceHolder is active, it means you could not write anything except the place
holder. Now, we are going to put something in the place holder. Type “This is my
Home Page”, do the same as what you created in your home web form and type that relate
in every pages.
Questions:
Design a college website(minimum 4 pages)
Design a company website(minimum 4 pages)
Objectives:
To understan
ADO.Net provides a bridge between the front end controls and the back end database. The
ADO.Net objects encapsulate all the data access operations and the controls interact with
these objects to display data, thus hiding the details of movement of data.
The data set represents a subset of the database. It does not have a continuous
connection to the database. To update the database a reconnection is required. The
DataSet contains DataTable objects and DataRelation objects. The DataRelation objects
represent the relationship between two tables.
Properties Description
CaseSensitive Indicates whether string comparisons within the data tables are
case-sensitive.
Container Gets the container for the component.
DataSetName Gets or sets the name of the current data set.
DefaultViewManager Returns a view of data in the data set.
DesignMode Indicates whether the component is currently in design mode.
EnforceConstraints Indicates whether constraint rules are followed when
attempting any update operation.
Events Gets the list of event handlers that are attached to this
component.
ExtendedProperties Gets the collection of customized user information associated
with the DataSet.
HasErrors Indicates if there are any errors.
IsInitialized Indicates whether the DataSet is initialized.
Locale Gets or sets the locale information used to compare strings
within the table.
Namespace Gets or sets the namespace of the DataSet.
Prefix Gets or sets an XML prefix that aliases the namespace of the
DataSet.
Relations Returns the collection of DataRelation objects.
Tables Returns the collection of DataTable objects.
Methods Description
AcceptChanges Accepts all changes made since the DataSet was loaded
or this method was called.
BeginInit Begins the initialization of the DataSet. The initialization
occurs at run time.
Clear Clears data.
Clone Copies the structure of the DataSet, including all
DataTable schemas, relations, and constraints. Does not
copy any data.
Copy Copies both the structure and data.
CreateDataReader() Returns a DataTableReader with one result set per
DataTable, in the same sequence as the tables appear in
the Tables collection.
CreateDataReader(DataTable[]) Returns a DataTableReader with one result set per
DataTable.
EndInit Ends the initialization of the data set.
Equals(Object) Determines whether the specified Object is equal to the
current Object.
Finalize Free resources and perform other cleanups.
GetChanges Returns a copy of the DataSet with all changes made
since it was loaded or the AcceptChanges method was
called.
GetChanges(DataRowState) Gets a copy of DataSet with all changes made since it
was loaded or the AcceptChanges method was called,
filtered by DataRowState.
GetDataSetSchema Gets a copy of XmlSchemaSet for the DataSet.
GetObjectData Populates a serialization information object with the data
needed to serialize the DataSet.
GetType Gets the Type of the current instance.
GetXML Returns the XML representation of the data.
GetXMLSchema Returns the XSD schema for the XML representation of
the data.
HasChanges() Gets a value indicating whether the DataSet has
changes, including new, deleted, or modified rows.
HasChanges(DataRowState) Gets a value indicating whether the DataSet has
changes, including new, deleted, or modified rows,
filtered by DataRowState.
IsBinarySerialized Inspects the format of the serialized representation of the
DataSet.
Load(IDataReader, Fills a DataSet with values from a data source using the
LoadOption, DataTable[]) supplied IDataReader, using an array of DataTable
instances to supply the schema and namespace
information.
Load(IDataReader, Fills a DataSet with values from a data source using the
LoadOption, String[]) supplied IDataReader, using an array of strings to supply
the names for the tables within the DataSet.
Merge() Merges the data with data from another DataSet. This
method has different overloaded forms.
ReadXML() Reads an XML schema and data into the DataSet. This
method has different overloaded forms.
ReadXMLSchema(0 Reads an XML schema into the DataSet. This method
has different overloaded forms.
RejectChanges Rolls back all changes made since the last call to
AcceptChanges.
WriteXML() Writes an XML schema and data from the DataSet. This
method has different overloaded forms.
WriteXMLSchema() Writes the structure of the DataSet as an XML schema.
This method has different overloaded forms.
The DataTable class represents the tables in the database. It has the following important
properties; most of these properties are read only properties except the PrimaryKey
property:
Properties Description
ChildRelations Returns the collection of child relationship.
Columns Returns the Columns collection.
Constraints Returns the Constraints collection.
DataSet Returns the parent DataSet.
DefaultView Returns a view of the table .
ParentRelations Returns the ParentRelations collection.
PrimaryKey Gets or sets an array of columns as the primary key for the
table.
Rows Returns the Rows collection.
Methods Description
AcceptChanges Commits all changes since the last AcceptChanges.
Clear Clears all data from the table.
GetChanges Returns a copy of the DataTable with all changes made since
the AcceptChanges method was called.
GetErrors Returns an array of rows with errors.
ImportRows Copies a new row into the table.
LoadDataRow Finds and updates a specific row, or creates a new one, if not
found any.
Merge Merges the table with another DataTable.
NewRow Creates a new DataRow.
RejectChanges Rolls back all changes made since the last call to
AcceptChanges.
Reset Resets the table to its original state.
Select Returns an array of DataRow objects.
The DataRow object represents a row in a table. It has the following important properties:
Properties Description
HasErrors Indicates if there are any errors .
Items Gets or sets the data stored in a specific column .
ItemArrays Gets or sets all the values for the row.
Table Returns the parent table .
Methods Description
AcceptChanges Accepts all changes made since this method was called.
BeginEdit Begins edit operation.
CancelEdit Cancels edit operation.
Delete Deletes the DataRow .
EndEdit Ends the edit operation.
GetChildRows Gets the child rows of this row.
GetParentRow Gets the parent row.
GetParentRows Gets parent rows of DataRow object.
RejectChanges Rolls back all changes made since the last call to
AcceptChanges.
The DataAdapter object acts as a mediator between the DataSet object and the database.
This helps the data set to contain data from more than one database or other data source.
The DataReader object is an alternative to the DataSet and DataAdapter combination. This
object provides a connection oriented access to the data records in the database. These
objects are suitable for read-only accesses, such as populating a list and then breaking the
connection.
The DbConnection object represents a connection to the data source. The connection
could be shared among different command objects.
The DbCommand object represents the command or a stored procedure sent to the
database from retrieving or manipulating data.
Example:
So far, we have used tables and databases already existing in our computer. In this
example, we will create a table, add column, rows and data into it and display the table
using a GridView object.
</div>
</form>
</body>
</html>
namespace createdatabase
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet ds = CreateDataSet();
GridView1.DataSource = ds.Tables["Student"];
GridView1.DataBind();
}
}
private DataSet CreateDataSet()
{
//creating a DataSet object for tables
DataSet dataset = new DataSet();
// adding columns
AddNewColumn(Students, "System.Int32", "StudentID");
AddNewColumn(Students, "System.String", "StudentName");
AddNewColumn(Students, "System.String", "StudentCity");
// adding rows
AddNewRow(Students, 1, "M H Kabir", "Kolkata");
AddNewRow(Students, 1, "Shreya Sharma", "Delhi");
AddNewRow(Students, 1, "Rini Mukherjee", "Hyderabad");
AddNewRow(Students, 1, "Sunil Dubey", "Bikaner");
AddNewRow(Students, 1, "Rajat Mishra", "Patna");
return Students;
}
The application first creates a data set and binds it with the grid view control using
the DataBind() method of the GridView control.
The Createdataset() method is a user defined function, which creates a new DataSet
object and then calls anther user defined method CreateStudentTable() to create the
table and add it to the Tables collection of the data set.
The CreateStudentTable() method calls the user defined methods AddNewColumn()
and AddNewRow() to create the columns and rows for the table as well as to add
data to the rows.
When the page is run, it returns the rows of the table so created:
Conclusion: Hence we have studied ADO .Net ASP.Net.