0% found this document useful (0 votes)
3 views113 pages

C# and .NET TECHNOLOGIES notes

The document outlines a syllabus for a course on C# and .NET technologies, covering topics such as web technologies, C# programming, object-oriented programming concepts, and VB.NET. It includes detailed explanations of web components, HTML basics, and scripting languages, emphasizing both client-side and server-side scripting. Additionally, it discusses application development using ADO.NET and various web technologies like XML, CSS, and JavaScript.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
3 views113 pages

C# and .NET TECHNOLOGIES notes

The document outlines a syllabus for a course on C# and .NET technologies, covering topics such as web technologies, C# programming, object-oriented programming concepts, and VB.NET. It includes detailed explanations of web components, HTML basics, and scripting languages, emphasizing both client-side and server-side scripting. Additionally, it discusses application development using ADO.NET and various web technologies like XML, CSS, and JavaScript.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 113

Subject: C# and .

NET Technologies

Syllabus

Unit 1: Introduction to .Net Technologies: Introduction to Web Technologies. HTML Basics, Scripts.
Sample Programs. Advantages and Disadvantages of Client-side and Server-side Scripts. Overview of
Client-side and Overview of Technologies and Server-side Technologies.

Introduction to C#: Overview of C#, Literals, Variables, Data Types, Operators, Expressions, Control
Structures-Methods, Arrays, Strings, Structures, Enumerations.

Unit 2: OOPS with C#: Classes, Objects, Inheritance, Polymorphism, Interfaces, Operator Overloading
Delegates, Events, Errors and Exceptions.

Introduction to VB.NET: Introduction VB.NET -IDE – Creating a shortcut to start VB.NET.


Maneuverings the Toolbar Auto-hide, Docking and Undocking, Placing and Resizing the Windows,
Forms, Properties Window and Solution Explorer. Writing and Event Procedure. Execution Basic
Keywords, Data Types. VB.NET statements. Conditional statements: If Else, Select Case, Switch and
Choose Loops: Do, For Next, For Each Next, While loop. Arrays.

Unit 3: Application Development on .NET:C#.NET: Building Windows Applications, VB.NET:


Windows Forms. Working with Controls, Timer, Picture-box, Group-box, Combo-box, Horizontal and
Vertical Scrollbar, Numeric-up-down, Track-bar, and Progress-bar. Subroutines and Functions in
VB.NET. Database applications

ADO .NET Connectivity: Introduction to ADO.NET, ADO vs ADO.NET. Architecture: Data reader, Data
adopter, Accessing Data with ADO.NET. Programming Web Applications with Web Forms, ASP .NET
applications with ADO.NET

1
Unit 1
Introduction to .NET Technologies
Introduction to Web Technologies
Web Technology:

Web Technology refers to the various tools and techniques that are utilized in the process of
communication between different types of devices over the internet. A web browser is used to access
web pages. Web browsers can be defined as programs that display text, data, pictures, animation, and
video on the Internet.

WWW has allowed for the access of information that would have been impossible to find or may have
been difficult to find without the www.

The Internet and World Wide Web (WWW)

Internet: The Internet is the massive network of networks that connects millions of computers
worldwide.

WWW: The World Wide Web, abbreviated as WWW and commonly known as the Web, is a system of
interlinked hypertext documents accessed via the Internet. With a web browser, one can view web
pages that may contain text, images, videos, and other multimedia and navigate between them via
hyperlinks.

Computers connected to the Internet can communicate with one another with a number of protocols
such as HTTP, SMTP (Simple Mail Transfer Protocol), FTP (File Transfer Protocol), IRC (Internet relay
chat), IM (instant messaging), Telnet, and P2P (peer-to-peer).

Components of Web Technology


Web Technology can be classified into the following sections:

World Wide Web (WWW): The World Wide Web is based on several different technologies: Web
browsers, Hypertext Markup Language (HTML) and Hypertext Transfer Protocol (HTTP).

Web Pages: A webpage is a digital document that is linked to the World Wide Web and viewable by
anyone connected to the internet has a web browser.

Website: A collection of web pages which are grouped together and usually connected together in
various ways. Often called a "web site" or simply a "site.“

Web Browser: A web browser takes you anywhere on the internet. It retrieves information from other
parts of the web and displays it on your desktop or mobile device. The information is transferred using
the Hypertext Transfer Protocol, which defines how text, images and video are transmitted on the web.

Examples of Web Browser:- Internet Explorer, Google Chrome, Fire Fox , Safari.

Web Server: A Web server is a program or computer machine that generates and transmits responses
to client requests for Web resources using HTTP protocol. Every computer on the Internet that contains
a Website must have a Web server program.

Example: Apache HTTP Server, Microsoft Internet Information Services (IIS).

2
Web Development: Web development refers to the building, creating, and maintaining of websites. It
includes aspects such as web design, web publishing, web programming, and database management. It
is the creation of an application that works over the internet i.e. websites.

Two Types Web Pages

 Static pages show the same content each time they are viewed. Static web pages are very
simple. It is written in languages such as HTML, JavaScript, CSS, etc.
 Dynamic pages have content that can change each time they are accessed. Dynamic Web Pages
are written in languages such as CGI, AJAX, ASP, ASP.NET, etc. In dynamic web pages, the
Content of pages is different for different visitors.

URL (Uniform Resource Locator)

URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on the
Internet.

URL strings consist of three parts (substrings):

1. network protocol: Typical URL protocols include

http:// and ftp:// .

2. host name or address: identifies a computer or other network device.

3. file or resource location: These substrings are separated by special characters as follows:

protocol :// host /location

Example: http://www.programiz.com

How does Web Servers Work?

The client computer will request data or services on the server. Then after the request is received, the
server will process it and the results are sent back to the client computer.

o Obtaining the IP Address from domain name: Our web browser first obtains the IP address
the domain name
o Browser requests the full URL : After knowing the IP Address, the browser now demands a
full URL from the web server.
o Web server responds to request: The web server responds to the browser by sending the
desired pages.

3
IP Address: IP stands for "Internet Protocol,” it is a unique address that identifies a device on the
internet or a local network which is the set of rules governing the format of data sent via the internet or
local network.

Examples of Web Servers:

 Apache HTTP Server:

The Apache HTTP Server, commonly referred to as Apache is a web server software program which
gave the initial boost for the growth of the World Wide Web. The server is aimed at serving a great deal
of widely popular modern web platforms/operating systems such as Unix, Windows, Linux, Mac OS x
etc.

 Microsoft Internet Information Services (IIS):

IIS is one of the components of Microsoft Windows and is Microsoft's implementation of a web server.
The protocols supported include HTTP, HTTPS, FTP, FTPS & SMTP .t's estimated that around 25% of all
websites utilize IIS.

Protocol

A protocol is a set of rules that govern data communications .A protocol defines what is communicated,
how it is communicated, and when it is communicated. It represents an agreement between the
communicating devices.

HTTP Protocol (Request-Response Protocol)

 HTTP stands for Hyper Text Transfer Protocol it is the language of the Web.
 HTTP is a protocol used for communication between web browsers and web servers.
 When a web page has this prefix, then your links, text, and pictures should work in your web
browser
 HTTP functions as a request-response protocol in the client-server computing model.
 A web browser, for example, may be the client and an application running on a computer
hosting a web site maybe the server.
 The client submits an HTTP request message to the server.
 The server, which provides resources such as HTML (Hyper Text Markup Language) files and
other content, or performs other functions on behalf of the client, returns a response message to
the client.

API (Application Programming Interface)

APIs are mechanisms that enable two software components to communicate with each other using a set
of definitions and protocols. In other words, an API is the messenger that delivers your request to the
provider that you're requesting it from and then delivers the response back to you. For example, the
weather bureau's software system contains daily weather data. The weather app on your phone “talks”
to this system via APIs and shows you daily weather updates on your phone.

Gateway

The gateway converts information, data or other communications from one protocol or format to
another. A router may perform some of the functions of a gateway. An Internet gateway can transfer
communications between an enterprise network and the Internet. For example, if a computer on the
Internet sends an email to another, the gateway converts the message from one protocol to another and
sends it back.

4
XML:XML stands for Extensible Markup Language. It is a text-based markup language derived from
Standard Generalized Markup Language (SGML). XML tags identify the data and are used to store and
organize the data, rather than specifying how to display it like HTML tags, which are used to display the
data.

Some of the Web Technologies:(Explaination refer pageno.13)

 HTML (Hyper Text Markup Language)


 XML (Extensible Markup Language)
 CSS (Cascading Style Sheets)
 JavaScript
 Java
 VBScript(Visual-Basic Script)
 PHP(Hypertext Pre-processor)
 C#(C-Sharp)
 ASP(Active Server Pages)
 ASP.NET(Active Server Pages)

HTML Basics
 HTML stands for Hyper Text Markup Language.
 HTML is the standard Markup language for creating Web pages.
 HTML describes the structure of a Web page.
 HTML consists of a series of elements.
 HTML elements tell the browser how to display the content.
 HTML elements label pieces of content such as "this is a heading", "this is a paragraph", "this is a
link", etc.
 HTML uses HTML Tags that are integrated into text document.
 HTML has opening tag with respective closing tag.
 HTML code can be written in an text editor like Notepad.
 Save the file with .htm or .html extension.
 Open the file with any web browser to see the html page output.

HTML Program Format

<!DOCTYPE html>
<html>
<body>
-------------------------
-------------------------
-------------------------
</body>
</html>

HTML Sample Program

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>

<h1>My First Heading</h1>

5
<p> My first paragraph </p>

</body>
</html>

Explaination of HTML Tags


 Every HTML document begins with a HTML document tag. The <!DOCTYPE> declaration
represents the document type, and helps browsers to display web pages correctly.
 <html>: Every HTML code must be enclosed between basic HTML tags. It begins with <html>
and ends with </html> tag. It is a root element.
 <head>: The head tag comes next which contains all the header information of the web page or
documents like the title of the page
 <title>: We can mention the title of a web page using the <title> tag. This is header information
and hence is mentioned within the header tags
 <body>: The body tag contains the actual body of the page which will be visible to all the users.
This opens with <body> and ends with </body>. All content enclosed within this tag will be
shown on the web page be it writings or images or audio or videos or even links
 HTML Headings: These tags help us to give headings to the content of a webpage. These tags
are mainly written inside the body tag. HTML provides us with six heading tags from <h1> to
<h6>. Every tag displays the heading in a different style and font size.
 <p>: HTML Paragraph: These tags help us to write paragraph statements on a webpage.
 <br>: HTML Break: – These tags are used for inserting a single line type break. It does not have
any closing tag. In HTML the break tag is written as <br>
 <hr>: HTML Horizontal :- The <hr> tag is used to break the page into various parts, creating
horizontal margins with help of a horizontal line running from the left to right-hand side of the
page.
 HTML Images: The image tag is used to insert an image into our web page. The source of the
image to be inserted is put inside the <img src= ”source_of_image“> tag.

Attributes in HTML

usually come in Attributes provide additional information about elements. Attributes are
always specified in the start tag. Attributes name/value pairs like: name="value".

The href Attribute: The <a> tag defines a hyperlink. The href attribute specifies the URL of the
page the link goes to.
Example: <a href="https://www.w3schools.com">Visit W3Schools</a>

The src Attribute: The <img> tag is used to embed an image in an HTML page. The src attribute
specifies the path to the image to be displayed.
Example: <img src="img_net.jpg" >

The <img> tag should also contain the width and height attributes, which specify the width and
height of the image (in pixels)
Example: <img src="img_net.jpg" width="500" height="600">

The alternate attribute <alt>: The required alt attribute for the <img> tag specifies an
alternate text for an image.
Example: <img src="img_net.jpg" alt="bca">

<style>: The style attribute is used to add styles to an element, such as color, font, size, and
more.

6
Example: <p style="color: red;">This is a red paragraph.</p>

<lang>: You should always include the lang attribute inside the <html> tag, to declare the
language of the Web page.
Example: <html lang="en">

Hyperlinks

It allows navigation from one page to another page which is used to link from one page to another
page. We use the <a> tag to define a hyperlink. In the <a> tag, the href attribute specifies the URL of the
page the link goes to. The href attribute consists of two components: the URL (actual link) and the
anchor text or clickable text that appears on the page.

Example:

<a href="https://www.naukri.com/learning/">Click to visit Naukri Learning</a>

<span> and <div> tags:

<span> tag: The <span> tag is an inline container used to mark up a part of a text, or a part of a
document.

Example: <p> Computer Science <span style=”color: red; font-weight bolder”>portal</span> for <span
style=”background color light-green;”>students</span>

<div> tag: It helps to separate our data in web page. We can create particular section for particular data
like text, images, header, footer etc. It is used to group large section of elements together.

Example of <div> tag


<html>
<head>
<style>
.myDiv {
border: 5px outset red;
background-color: lightblue;
text-align: center; }
</style>
</head>
<body>
<div class="myDiv">
<h2>This is a heading in a div element</h2>
<p>This is some text in a div element.</p>
</div>
</body>
</html>

HTML Tables:

The <table> tag defines an HTML table.

An HTML table consists of one <table> element and one or more <tr>, <th>, and <td> elements.

The <tr> element defines a table row, the <th> element defines a table header, and the <td> element
defines a table cell.

7
HTML Lists:

HTML lists allows web developers to group a set of related items in lists.

<ol> -> Ordered lists: Items in the list are numbered.

<ul> -> Unordered lists : Items in the list are bulleted.

<dl> -> tag defines the description lists.

HTML Forms:

The HTML <form> element is used to create an HTML form for user input.

The <form> element is a container for different types of input elements, such as: text fields, checkboxes,
radio buttons, submit buttons, etc.

List of tags HTML

8
Scripting Language or Scripts
A script or scripting language is a computer language that does not need the compilation step and is
rather interpreted one by one at runtime.

Scripts are often utilized to create dynamic web applications nowadays because they are linked to web
development.

It is embedded in an HTML web page, interpreted, and executed by a certain scripting engine.

Types of Scripting Language:

 Client-Side Scripting.
 Server-Side Scripting.

Client-Side Scripting

 Client-side means that the processing takes place on the user’s computer. It requires browsers
to run the scripts on the client machine without involving any processing on the server.
 The processing takes place on the end users computer. Client will request the server.The source
code is transferred from the web server to the users computer over the internet and run
directly in the browser. This script will allow the client’s browser to alleviate some of the
burden on your web server when running a web application.
 Client side scripting cannot be used to connect to the databases on the web server. Client-side
scripting is faster because it does not require interaction with the web server only interaction
done is receiving the data which was requested.
 The main tasks of Client side JavaScript are validating input, animation, manipulating UI
elements, applying styles, some calculations are done when you don't want the page to refresh
so often.
 Languages used: HTML, CSS, JavaScript, VBScript

Client  Front End  web browser(Google chrome ,internet explorer)

9
Server-Side Scripting

 Server-side means that the processing takes place on a web server and the script is not visible to
the user.
 A user's request is fulfilled by running a script directly on the web server to generate dynamic
HTML pages. This HTML is then sent to the client browser. It is usually used to provide
interactive web sites that interface to databases or other data stores on the server .
 It helps to provide response to every request that comes from user client. Server-side scripting
is associated with accessing data, error handling, and the fastest processing of the data. It is
processed and communicates with the server.
 Therefore, it is secure. It is generally used to create dynamic websites, send responses to user
queries, or provide data, etc.
 The most common and widely used server-side scripting programming language is C#, PHP,
Java, ASP.NET, and many more.

Server Back End  Web Server

Client-Side and Server-Side Scripting Example:

Consider a simple example. Let's say you are completing an online form, and you have to type in your
phone number. Logically, that should only consist of numbers, and it may require a very specific format,
such as this: 5552347890.

The form will not allow you to enter characters that are not numbers, and it will not allow you to use a
different format. This is the result of a client-side script. The script responds immediately to your
typing, checks your input, and provides a response before you actually submit the form.

Consider the example of logging into your bank account online. You can go to the bank's homepage and
fill in your username and password. Then you click the 'login' button. This sends a request to the server.
The server checks your login credentials and pulls up your account information - this is when the
scripts are run. The server then creates an HTML page to present you with your account details.

Client-Side and Server Side Architecture diagram:

CLIENT

SERVER

10
Advantages of Scripting Language

There are many advantages of using a scripting language.

 Open source and Free: First, they are open source. Therefore, anyone around the world can
use it and contribute to it.
 Easy to use: Second, if you are a beginner, they are a great way to start with programming
languages, as they are quite easy to learn and code.
 Lighter memory requirement: As we know that most scripting languages use an interpreter,
and unlike compilers, no executable file is stored, and hence, they require less memory.
 Portable and platform Independent: They are portable, i.e., can run on different operating
systems.
 Interactivity: It helps to make web pages more interactive by adding combinations and
visualization interfaces. The use of scripting languages is demanded by modern web pages. It
includes background and foreground colors and so on, which helps to create enhanced web
pages.
 Scripts are also used as a prototype before building an actual program.
 It directly executes the files without needing compilation but sometimes may be required
to compile when necessary.
 Functionality: Scripting languages contain different libraries, which help to create new
applications in web browsers. They are different from normal programming languages.

Disadvantages of Scripting Language

 It enables users to view and code that may be prohibited by some companies.
 These languages did not compile the file and interpret it directly, which need to install an
interpreter or separate program by the users before running the script.
 Compared with a compiled program, scripting languages may be slow in some situations.
 In the scripting languages, the interpreter analyzes each statement line by line during execution,
therefore don’t perform many optimizations to execute the code faster.
 One main disadvantage of the graphic user interface is that they are expensive and takes much
time to develop.
 It is not supported by all browsers. if no alternative is given for the script than the user might
get an error.

Sample Programs
<html>
<body>
<script language= “javascript” type “text/javascript>
document.write (“hello world”);
</script>
</body>
</html>

Each of the below method have different ways of outputting the content.
 console.log () for debugging the javascript code.

11
 document.write() is used when we want to print the content/output.
 alert ()

Javascript program to add two numbers


<html>
<body>
<script language= “javascript” type “text/javascript>
var a= 5;
var b =6;
console.log(“The sum of “+a+” and “+b” is: “+c);
</script>
</body>
</html>

Javascript program to find area of triangle


<html>
<body>
<script language= “javascript” type “text/javascript>
var base =8;
var height = 3;
var area= (base*height)/2;
console.log(area);
</script>
</body>
</html>

Javascript program to find square root of a number


<html>
<body>
<script language= “javascript” type “text/javascript>
var a=prompt (“please enter a number:”);
var b= Math.sqrt(a);
console.log(b);
</script>
</body>
</html>

12
Overview of Client-Side Technologies

Languages for Client-Side Scripting

 Javascript: JavaScript is a famous scripting language used to create magic on the sites to make
the site interactive for the user.
 VBScript: VBScript (Visual Basic Script) is a general-purpose, lightweight and active scripting
language mainly used to give functionality to webpages.
 HTML: HTML stands for Hypertext Markup Language. It is used to design the front-end portion
of web pages using a markup language.
 CSS: Cascading Style Sheets fondly referred to as CSS is a simply designed language intended to
simplify the process of making web pages presentable. CSS allows you to apply styles to web
pages.
 AJAX : Ajax is an acronym for Asynchronous Javascript and XML. It is used to communicate with
the server without refreshing the web page and thus increasing the user experience and better
performance.
 JQuery : jQuery is a lightweight, "write less, do more", JavaScript library. The purpose of jQuery
is to make it much easier to use JavaScript on your website.

Overview of Server-Side Technologies

Languages for Server-Side Scripting

 PHP: PHP(Hypertext Pre-processor) is a server-side scripting language designed specifically for


web development. Since PHP code executed on the server-side.
 C++: C++ is a powerful general-purpose programming language. It can be used to develop
operating systems, browsers, games, and so on.
 C#: C# is a general-purpose, modern and object-oriented programming language pronounced as
“C sharp”.
 Java: Java is one of the most popular and widely used programming languages and platforms. It
is highly scalable. Java components are easily available.
 Python: Python is a programming language that lets you work quickly and integrate systems
more efficiently.
 Ruby: Ruby is probably most famous for its use in web development , it has many other uses,
too. Ruby is a highly versatile and portable language.
 ASP.NET: NET is a developer platform made up of tools, programming languages, and libraries
for building many different types of applications. ASP.NET extends the .NET developer platform
with tools and libraries specifically for building web apps.
 DBMS: The software which is used to manage database is called Database Management System
(DBMS).

13
Introduction to C#

 C# is pronounced as "C-Sharp". It is an object-oriented programming language provided by


Microsoft that runs on .Net Framework.
 C# is a modern, general-purpose and object-oriented programming Language developed by
Microsoft led by Anders Hejlsberg and his team and was approved by the European Computer
Manufacturers Association (ECMA) and International Standards Organization (ISO).
 C# was mainly designed for Common Language Infrastructure(CLI) which consists of the executable
code and runtime environment that allows use of various high-level languages on different
computer platforms and architectures.

Features of C#

 Simple: C# is a simple language in the sense that it provides structured approach (to break the
problem into parts).
 Modern programming language: C# programming is based upon the current trend and it is
very powerful and simple for building scalable, interoperable and robust applications.
 Object oriented: C# is object oriented programming language. OOPs makes development and
maintenance easier where as in Procedure-oriented programming language it is not easy to
manage if code grows as project size grow.
 Type safe: C# is type safe code can only access the memory location that it has permission to
execute. Therefore it improves a security of the program
 Interoperability: Interoperability process enables the C# programs to do almost anything that
a native C++ application can do.
 Scalable and Updateable: C# is automatic scalable and updateable programming language. For
updating our application we delete the old files and update them with new ones.
 Structured programming language: C# is a structured programming language in the sense
that we can break the program into parts using functions. So, it is easy to understand and
modify.
 Rich Library: C# provides a lot of inbuilt functions that makes the development fast.
 Fast speed: The compilation and execution time of C# language is fast.

Applications of C#
 Games using Unity
 Web Applications Client-Server Applications
 Windows Applications: Applications that run on desktops
 Web Services Applications
 Console Applications
 Class Libraries

14
Difference between C++ and C#

C# Program Structure

C# Program Syntax

using System;
namespace <namespace_name>
{
class <class_name>
{
static void Main(string[] args)
{
---------------------------
---------------------------
}
}
}

C# Program Structure Example:

using System;
namespace Sample
{
class Program {
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}}

15
A C# program consists of the following parts:
The first line of the program using System; - the using keyword is used to include the System
namespace in the program. Any construct used in program is defined within System namespace.
The next line has the namespace declaration. A namespace is a collection of classes. The Sample
namespace contains the class Program.
C# is an object-oriented programming language hence at least one class must be defined. The class
Program contains the data and method definitions that your program uses.
The main () is a method of Program class is the entry point of the console application.
static() : There is no object of the class available at the time of runtime, and because of that, we have to
define the main() method as static. To load the class into the memory and call the main method.
void() : The main() method doesn't return anything, and its return type is void. The main() method
doesn't return anything to make things simple.
Console.WriteLine is a static method which is used to display a text on the console.

Literals
 The fixed values are called literals. The constants refer to fixed values that the program may not
alter during its execution.
 The fixed values are called as Literal. Literal is a value that is used by the variables. Values can
be either an integer, float or string, etc.

// Here 100 is a constant/literal.


int x = 100;

Literals can be of the following types:


 Integer Literals
 Floating-point Literals
 Character Literals
 String Literals
 Null Literals
 Boolean Literals

Integer Literals: A literal of integer type is know as the integer literal. It can be octal, decimal, binary,
or hexadecimal constant.
A suffix can also be used with the integer literals like U or u are used for unsigned numbers while l or
are used for long numbers.
Example: int x = 101;
int x = 0146;
int x = 0123F;
int x = 0b101;

Floating-point Literals: The literal which has an integer part, a decimal point, a fractional part, and an
exponent part is known as the floating-point literal.
Example: double d = 3.14145
Character Literals: For character data types we can specify literals in 3 ways:
Single quote: We can specify literal to char data type as single character within single quote.
Example: char ch = 'a';
Unicode Representation: We can specify char literals in Unicode representation ‘\uxxxx’. Here xxxx
represents 4 hexadecimal numbers.

16
Example: char ch = '\u0061';// Here /u0061 represent a.
Escape Sequence: Every escape character can be specified as char literals.
Example: char ch = '\n';
String Literals: Literals which are enclosed in double quotes(“ ”) are known as the String literals
Example: String s1 = "Hello Geeks!";
Boolean Literals: Only two values are allowed for Boolean literals i.e. true and false.
Example: bool a = true;
bool b = false;
The null literal evaluates to the null value, which is used to denote a reference not pointing at any
object or array, or the absence of a value.

Variables
o A variable is a name of memory location. It is used to store data. Its value can be changed and it
can be reused many times.
o It is a way to represent memory location through symbol so that it can be easily identified.
o Each variable in C# has a specific type, which determines the size and layout of the variable's
memory the range of values that can be stored within that memory and the set of operations
that can be applied to the variable.

Syntax for declaring variable:


Data type variable_list;

The basic variable type available in C# can be categorized as:


Decimal types: decimal
Boolean types : True or false value, as assigned
Integral types : int, char, byte, short, long
Floating point: float and double
Nullable types: Nullable data types

The example of declaring variable is given below:


int i, j;
double d;
float f;
char ch;

Rules for defining variables:


 A variable can have alphabets, digits and underscore.
 A variable name can start with alphabet and underscore only. It can't start with digit.
 No white space is allowed within variable name.
 A variable name must not be any reserved word or keyword e.g. char, float etc.

Valid variable names:


int x;
int _x;
int k20;

17
Invalid variable names:

int 4;
int x y;
int double;

What is a Constant variable?


A variable whose value can not be changed during the execution of the program is called a constant
variable, which means we cannot assign values to the constant variable at run time. Instead, it must be
assigned at the compile time.

In the above diagram, we can see the Constants are of two types
 Compile time constants (const)
 Runtime constants (Readonly)

Compile time constants:


The compile time constants are declared by using the const keyword, in which the value can not be
changed during the execution of the program. It must be assigned a value at the time of declaration.
Syntax:
int const a=10;
When const is used?
The const is used when its value is absolutely constant. Such PI values cannot be changed, but according
to your needs, you can use it as you wish rather than declaring PI values.

Example:
using System;
class Program {
public const int myvar = 10;
public static void Main()
{
Console.WriteLine("The value of myvar: ", myvar);
}
}

Runtime constants (Readonly):


The Run time constants are declared by using the Readonly keyword which value cannot be changed
during the execution of the program. It's not just to assign a value at the time of declaration, we can also
assign the value for read-only through the constructor.
Syntax:
int readonly a;
a=0;
Readonly allows , readonly constant as well as non-readonly constant variables into the expression.

18
int readonly a=10;
int b=1;
int readonly c=a+b;
When readonly is used ?
We can use Readonly when its value is not an absolute constant, which means it can be changed
frequently, such as dollars vs INR.

Example:
using System;
class Prog
{
public readonly int myvar1;
public GFG (int b)
{
myvar1 = b;
Console.WriteLine("Display value of myvar1 ", myvar1);
}
static public void Main()
{
Prog obj1 = new Prog (100);
}
}

ReadOnly Keyword Const Keyword


In C#, readonly fields can be created In C#, constant fields are created using const .
using readonly keyword keyword.
ReadOnly is a runtime constant. Const is a compile time constant.
The value of readonly field can be changed. The value of the const field can not be changed.
It cannot be declared inside the method. It can be declared inside the method .

Data Types in C#

Data types specify the type of data that a valid C# variable can hold.

19
Value Data Type
In C#, the Value Data Types will directly store the variable value in memory The value data types are
integer-based and floating-point based. C# language supports both signed and unsigned literals.
There are 2 types of value data type in C# language.
1) Predefined Data Types - such as Integer, Boolean, Float, etc.
2) User defined Data Types - such as Structure, Enumerations, etc.
Structure: In C#, a structure is a value type data type. It helps you to make a single variable hold related
data of various data types. The struct keyword is used for creating a structure.
Enumerations: An enumeration is a set of named integer constants. An enumerated type is declared
using the enum keyword
The memory size of data types may change according to 32 or 64 bit operating system.

Reference Data Type


The reference data types do not contain the actual data stored in a variable, but they contain a reference
to the variables.
If the data is changed by one of the variables, the other variable automatically reflects this change in
value.
There are 2 types of reference data type in C# language.
1) Predefined Types - such as Objects, String.
Object: It is a basic unit of Object-Oriented Programming and represents real-life entities. A
typical C# program creates many objects, which as you know, interact by invoking methods.
String: Strings are used for storing text. A string variable contains a collection of characters
surrounded by double quotes
2) User defined Types - such as Classes, Interface.
Class: A class is a user-defined blueprint or prototype from which objects are created. Basically,
a class combines the fields and methods
Interface: Interface in C# is a blueprint of a class. It is like abstract class because all the
methods which are declared inside the interface are abstract methods.

Pointer Data Type


The pointer in C# language is a variable, it is also known as locator or indicator.The Pointer Data Types
will contain a memory address of the variable value.

Symbols used in pointers:


& (ampersand sign): Address operator - Determine the address of a variable.
* (asterisk sign): Indirection operator - Access the value of an address.
Example:
int * a; //pointer to int
char * c; //pointer to char

20
Boxing and Unboxing
The conversion of the value type to the reference type is known as boxing . The boxing is also
considered as the implicit conversion that it is used in any object type.
Example:
Boxing:
int i = 123;
object o = I; // boxing

Example Program:
using System;
class Box
{
static public void Main() // main method
{
int val = 1000;
object obj1 = val; // Boxing technique
val = 500; // the changing of value
Console.WriteLine("Value Typed - The type value of number is : {0}", val);
Console.WriteLine("Object Typed - The type value of obj1 is : {0}", obj1);
}
}

Unboxing
The unboxing in the c# language is vice versa of the Boxing. It is the process of converting the
Reference Type data type variable to the Value Typed data type variable. This entire process is
known as the Unboxing terminology in c#.
The unboxing is also considered as the explicit conversion that it is used in any object type
process.
Example
UnBoxing:
o = 123;
i = (int)o; // unboxing

Example Program:
using System;
class Unbox
{
static public void Main() // Main method
{
int val = 10; // assigning the value 10 to the val
object obj1 = val; // Boxing technique
int i = (int)obj1; // unboxing technique
Console.WriteLine("The Value of obj1 object is : " + obj1); //
Console.WriteLine("The Value of I is : " + i);
}
}

21
Operators in C#

An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. C# has rich set of built-in operators and provides the following type of operators −
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Miscallenous Operators/Special Operators.

Arithmetic Operators:
These are used to perform arithmetic/mathematical operations on operands.
Example:
using System;
namespace Arithmetic
{
class Prog
{
static void Main()
{
int result;
int x = 10, y=20;
result = (x + y);
Console.WriteLine("Addition Operator: " + result);
result = (x - y);
Console.WriteLine("Subtraction Operator: " +
result);
result = (x * y);
Console.WriteLine("Multiplication Operator: "+
result);
}
}
}

Relational Operators:
Relational operators are used to check the relationship between two operands. If the relationship is true
the result will be true, otherwise it will result in false.
Example:
using System;
namespace Relational
{
class Prog
{
static void Main()
{
bool result;
int x = 5, y = 10;
result = (x == y);
Console.WriteLine("Equal to Operator: " + result);
result = (x > y);

22
Console.WriteLine("Greater than Operator: " + result);
result = (x < y);
Console.WriteLine("Less than Operator: " + result);
}
}
}

Logical Operators:
They are used to combine two or more conditions/constraints or to complement the evaluation of the
original condition in consideration.
Example:
using System;
namespace Logical
{
class Prog
{
static void Main()
{
bool a = true, b = false, result;
result = a && b;
Console.WriteLine("AND Operator: " + result);
result = a || b;
Console.WriteLine("OR Operator: " + result);
result = !a;
Console.WriteLine("NOT Operator: " + result);
}
}
}

Assignment Operators:
Assignment operators are used to assigning a value to a variable.
Example:
using System;
namespace OperatorsAppl
{
class Prog
{
static void Main() {
int a = 21;
int c;
c = a;
Console.WriteLine("Line 1 - Value of c = ", c);
c += a;
Console.WriteLine("Line 2 - Value of c = ", c);
c -= a;
Console.WriteLine("Line 3 - Value of c = ", c);
c *= a;
Console.WriteLine("Line 4 - Value of c = ", c);
c /= a;
Console.WriteLine("Line 5 - Value of c = ", c);
}
}}

23
Bitwise Operator:
In C#, there are 6 bitwise operators which work at bit level or used to perform bit by bit operations.
Example:
using System;
namespace OperatorsAppl {
class Program
{
static void Main() {
int a = 60; /* 60 = 0011 1100 */
int b = 13; /* 13 = 0000 1101 */
int c ;
c = a & b;
Console.WriteLine("Line 1 - Value of c is ", c );
c = a | b;
Console.WriteLine("Line 2 - Value of c is ", c);
c = a ^ b;
Console.WriteLine("Line 3 - Value of c is ", c);
}
}
}

Miscellaneous/Special Operators:

Example:
using System;
namespace OperatorsAppl {
class Program {
static void Main(string[] args) {
/* example of sizeof operator */
Console.WriteLine("The size of int is {0}", sizeof(int));
Console.WriteLine("The size of short is {0}", sizeof(short));
Console.WriteLine("The size of double is {0}", sizeof(double));

24
/* example of ternary operator */
int a, b;
a = 10;
b = (a == 1) ? 20 : 30;
Console.WriteLine("Value of b is {0}", b);

b = (a == 10) ? 20 : 30;
Console.WriteLine("Value of b is {0}", b);
Console.ReadLine();
}
}
}

Type Conversion
Type conversion is converting one type of data to another type. It is also known as Type Casting. In C#,
type casting has two forms −
Implicit type conversion − In implicit type conversion, the C# compiler automatically converts one
type to another. Generally, smaller types like int (having less memory size) are automatically converted
to larger types like double (having larger memory size).
char -> int -> long -> float -> double
Explicit type conversion − In explicit type conversion, we explicitly convert one type to another.
Generally, larger types like double (having large memory size) are converted to smaller types like int
(having small memory size).
double -> float -> long -> int -> char

Example for Implicit:


using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double

Console.WriteLine(myInt);
Console.WriteLine(myDouble);
}
}
}
Example for Explicit:
using System;

namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
double myDouble = 9.78;
int myInt = (int) myDouble; // Manual casting: double to int

Console.WriteLine(myDouble);

25
Console.WriteLine(myInt);
}
}
}

Expressions: An expression in C# is a combination of operands (variables, literals, method


calls) and operators that can be evaluated to a single value.
Example:
int a, b, c, sum;
sum = a + b + c;
if (age>=18 && age<58)
Console.WriteLine("Eligible to work");

Control Structures in C#

The control statements are used to control the flow of execution of the program.

Selection statements: Selection statements control program flow through the result of evaluating
boolean (true and false) values.
if, if-else, else-if, switch.
Iteration/looping statements: In the program, you perform some task or repeat some task on the
basis of iteration. Whenever the condition is true, the program knows to repeat. Once that condition is
false, then it’s time to stop repeating.
for , while, do while , foreach
Jump statements: Jumping statements are control statements that transfer execution control from one
point to another point in the program.
break , continue .

Selection statements
if condition
The if statement checks the given condition. If the condition evaluates to be true then the block of
code/statements will execute otherwise not.
Syntax
if(condition)
{
statement;// it must be true
}
An example
using System;
namespace MyApplication{
class demo{
int a=20,b=10;
static void Main()
{
if (a>b)
{
Console.WriteLine("a is greater than b");
}

26
}
}
}

If-else statement : The C# if-else statement also tests the condition. It executes the if block if condition
is true otherwise else block is executed.
Syntax
if(condition)
{
statement;//executes if condition is true
}
else
{
statement;// executes if condition is false
}
Example
using System;
namespace MyApplication{
class demo{
int a=20,b=10;
static void Main()
{
if (a>b)
{
Console.WriteLine("a is greater than b"); }
else {
Console.WriteLine("b is greater than a");
}
}
}
}

Else-if: If we have to specify two conditions which are related to each other, we can use the else if
statement to specify the second condition and its related code block.
Syntax
if(condition1)
{
statement;
}
else if(condition2)
{
statement;
}
else(condition3)
{
statement;
}
Example
using System;
namespace MyApplication{
class demo{
int a=20,b=10;
static void Main()
{

27
if (a>b)
{
Console.WriteLine("a is greater than b"); }
else if (b>a){
Console.WriteLine("b is greater than a");}
else {
Console.WriteLine("Both are equal");
}
}
}
}

Switch statement: The switch expression is evaluated once. The value of the expression is compared
with the values of each case. If there is a match, the associated block of code is executed.
Syntax
switch (expression)
{
case: 1
statement;
break;
case: 2
statement;
break;
.
.
default;
statement;
}
Example
using System;
namespace MyApplication{
class demo {
static void Main()
{
int year = 2;
switch (year)
{
case 1:
Console.WriteLine("2021");
break;
case 2:
Console.WriteLine("2022");
//it will output this we have switched it.
break;
case 3:
Console.WriteLine("2023");
break;
}
}
}

28
Iteration statements:
For loop : C# for loop is used to repeat a set of statements until a given condition is evaluated to False.
It is useful where you know in advance how many times program should iterate.
Syntax:
for(initialization; condition; increment/decrement)
{
statement;
}
Example:
using System;
class ForExample
{
static void Main()
{
for(int i=0;i<10;i++){
Console.WriteLine (i);
}
}
}

While loop: It is a simple loop. It executes till the code block while the condition is true. If the condition is
going to be false, the program will exit from the loop.
Syntax:
while(condition)
statement;
Example:
using System;
class WhileExample
{
static void Main()
{
int i=0;
while(i<10)
{
Console.WriteLine(i);
i++;
}
}
}

do while statement: This loop will execute the code block once, before checking if the condition is true,
then it will repeat the loop as long as the condition is true.
Syntax:
do
{
statement;
}
while (condition)
Example:
using System;
class DoWhileExample
{
static void Main()

29
{
int i = 1;
do{
Console.WriteLine(i);
i++;
}
while (i <= 10) ;
}
}

Foreach statement: The foreach loop is used to iterate over the elements of the collection. The
collection may be an array or a list. It executes for each element present in the array.
Syntax:
foreach(data_type var_name in
collection_variable)
{
// statements to be executed
}
Example:
using System;
class foreachExample
{
static void Main()
{
int[] a_array = new int[] { 1, 2, 3, 4, 5, 6, 7 };
foreach(int items in a_array)
{
Console.WriteLine(items);
}
}
}

Jump statements:
The break statement is used when one needs the code to terminate some statement and perhaps go to
the next.
Continue statements: These kinds of statements are mostly used when a programmer wants the
program to skip a certain part of an execution, for example in loop statements.
Example:
using System;
class demo{
static void Main()// Main Method
{
for (int i = 0; i< 7; i++)
{
if (i== 4)
continue;
Console.WriteLine(j);
}
}
}

30
Methods in C#
A method is a block of code which only runs when it is called. You can pass data, known as
parameters, into a method. Methods are used to perform certain actions, and they are also
known as functions.
To use a method, you need to −
o Define the method
o Call the method

Declaration of method:
Syntax:
<Access Specifier> <Return Type> <Method Name>(Parameter List)
{
Method Body
}
Method Invocation:
Method Invocation or Method Calling is done when the user wants to execute the method. The method
needs to be called for using its functionality. A method returns to the code that invoked it when:
o It completes all the statements in the method
o It reaches a return statement
o Throws an exception
Example:
static int Sum(int x, int y)
{
int a = x;
int b = y;
int result = a + b;
return result;
}
static void Main(string[] args)
{
int a = 12;
int b = 23;
int c = Sum(a, b);
Console.WriteLine("The Value of the sum is " + c);
}
}
}

Method parameters
Information can be passed to methods as parameter. Parameters act as variables inside the method.
They are specified after the method name, inside the parentheses. You can add as many parameters
as you want, just separate them with a comma.
Types of parameters
 Value parameter
 Reference parameter
 Output parameter
 Parameter arrays

31
Value parameter
 In value type parameter, the actual value gets passed to the function. Passing a value type
variable as parameter means, you are passing the copy of the value.Value parameters are the
parameters that are passed by value.
Example program
using System;
class program{
static void Cube(int x)
{
x = x * x * x;
Console.WriteLine("Value Within the Cube method : {0}", x);
}
static void Main()
{
int num = 5;
Cube(num);
Console.WriteLine( num);
Console.ReadKey();
}
}

Reference parameter
 Reference Type: A Reference type variable contains memory address of value.
 The ref is a keyword in C# which is used for passing the value types by reference. Or we can
say that if any changes made in this argument in the method will reflect in that variable
when the control return to the calling method.
Example program
using System;
class Program
{
static void Main(string[] args)
{
int val;
val = 4;
Console.WriteLine("Value Before :", val);
square(ref val);
Console.WriteLine("Value After : ", val);
}
static void square(ref int refParam) {
refParam *= refParam;
}
}
Output parameter
 A return statement can be used for returning only one value from a function. However, using
output parameters, you can return two values from a method. C# out parameter is used when a
method returns multiple values.
 When a parameter passes with the Out keyword/parameter in the method, then that method
works with the same variable value that is passed in the method call. If variable value changes,
the method parameter value also changes.

32
Example:
using System;
class program
{
static void arithmetic (int a, int b, out int s, out int p)
{
s=a+b;
p=a*b;
}
static void main( )
{
int a=10, b=20, sum, prod;
arithmetic (a,b, out sum, out prod);
}
}

Parameter Arrays/Param Arrays


 A parameter array can be used to pass an array of elements. You don't have to know the number
of elements in the array when you define the method. You use the param keyword to denote a
parameter array.
 C# Parameter array is declared with the params modifier.
 Parameter type must be declared as an array.
 Must be of a single-dimensional Array type.
 Empty array will be used if no value specified.

Example:
using System;
class parameterArrays
{
static void parray (params int[ ] a)
{
foreach ( int i in a)
Console. writeLine(i);
}
State void Main( )
{
int[ ] a={11,22,33};
parray(a);
parray( );
parray(10,20);
}
}

Nesting of methods
 A method can be called by using only its name by another method of the same class. This is
known as nesting of methods.
 A nested method is a method that is defined inside another method. A nested method is also
called a local method or a local function.
Example program
using System;
class Program
int a,b;

33
void getvalue()
{
a=4;
b=10;
}
Void show()
{
getvalue();
if(a>b)
{
Console.WriteLine(“A is greater value”);
}
else
{
Console.WriteLine(“B is greater value”);
}
}
static void main()
{
Program obj=new Program();
obj.show();
}
}
}

Method Overloading
 Having two or more methods with same name but different in parameters, is known as
method overloading in C#. Method Overloading is the common way of implementing
polymorphism.
 Method overloading is used when methods are required to perform similar tasks but using
different input parameters. Instead of defining two methods that should do the same thing,
it is better to overload .
Example program
using System;
namespace MethodOverload {
class Program {

// method with int parameter


void display(int a) {
Console.WriteLine("int type: " + a);
}

// method with string parameter


void display(string b) {
Console.WriteLine("string type: " + b);
}
static void Main() {

Program p1 = new Program();


p1.display(100);
p1.display("Programiz");
Console.ReadLine();
}
}}

34
Arrays in C#

 An array is a collection of items stored at contiguous memory locations. The idea is to store
multiple items of the same type together.
 The base index of array starts with 0 and ends with n-1.
 To access or retrieve index is used.
Declaration of Array

To declare an array in C# place a pair of square brackets after the variable type. The syntax is given
below :
type[] arrayname;
For Example:
int[] a;
float[] marks;
double[] x;
int[] m, n;
Memory allocation for arrays

After declaring an array, we need to allocate space by defining the size of array.
Syntax: arrayname = new type[size];
Example: a = new int[5];
marks = new float[6];
x = new double[10];
It is also possible to combine the two steps, declaration and memory allocation of array, into one as
shown below:
Example: int[] num = new int [5];
Initialization of array

 This step involves placing data into the array. Arrays are automatically assigned the default
values associated with their type.
 The initialization process is done using the array subscripts as shown:
Syntax: arrayname[subscript] = value;
Example:
num[0] = 5;
num[1] = 15;
num[2] = 52;
num[3] = 45;
 We can also initialize arrays automatically in the same way as the ordinary variables when they
are declared, as shown below:
Syntax: type[] arrayname = { list of values };
Example: int[] num = {5,15,52,45};

Types of Arrays

 Single Dimensional Array: A One-Dimensional Array is the simplest form of an Array in which
the elements are stored linearly and can be accessed individually by specifying the index value
of each element stored in the array. A single pair of the square bracket is used to represent a
single row (hence 1-D) of values under a single name.

Creating a 1-D Array/Syntax:


Syntax: int[] arr = new int[5];

35
Example Program:
using System;
class ArrayProg {
public static void Main()
{
int[] arr = { 20, 30, 40, 50, 60 };
for (int i = 0; i < arr.Length; i++)
{
Console.WriteLine( arr[i] );
}
}
}
 Multidimensional Array: It is also called rectangular arrays, A multidimensional array is an
array with more than two dimensions. In a matrix, the two dimensions are represented by rows
and columns. Each element is defined by two subscripts, the row index and the column index.
Creating a Multi-dimensional array
Syntax: int[,] arr = new int[3, 3]; //2d array
int[,,] arr= new int[3, 3, 3]; //3d array
Example Program:
using System;
class Multi_ArrayProg

{
public static void Main()
{
int[,] arr = new int[3, 3]; //initialization 3 rows and 3 columns
arr[0,1]=10;
arr[1,2]=20;
arr[2,0]=30;
int i, j;
for( i=0; i<3; i++){
for( j=0; j < 3; j++) {
Console.WriteLine ( arr[i, j] );
}
}
}
}

Jagged Array:
These types of arrays are mainly called "array of arrays". A jagged array is an array whose
elements are arrays, possibly of different sizes. The element size differs in the case of jagged
arrays.
Syntax: int[][] arr = new int[2][];
arr[0] = new int[4];
arr[1] =new int[6];
Example Program:
using System;
class JaggedArrayProg
{
public static void Main()
{
int[][] arr= new int[2][];
arr[0] = new int[] { 62, 24, 9, 37 };
arr[1] = new int[] { 43, 42, 68, 80, 15, 73 };

36
for (int i = 0; i < arr.Length; i++)
{
for (int j = 0; j < arr[i].Length; j++)
{
Console.WriteLine( arr[i][j] + " " );
}
}
}
}

Array Class

• It is defined in the System namespace.


• It is the base class to all arrays, and provides various properties and methods for working with
arrays.

Properties of the Array Class


The commonly used properties of the Array class −
1. IsFixedSize : Gets a value indicating whether the Array has a fixed size.
2. IsReadOnly : Gets a value indicating whether the Array is read-only.
3. Length : Gets a 32-bit integer that represents the total number of elements in all the dimensions
of the Array
4. LongLength : Gets a 64-bit integer that represents the total number of elements in all the
dimensions of the Array.
5. Rank : Gets the rank (number of dimensions) of the Array.

Methods of the Array Class


• Clear() : Sets a range of elements in the Array to zero, to false, or to null, depending on the
element type.
• Copy(Array, Array, Int32) : Copies a range of elements from an Array starting at the first
element and pastes them into another Array starting at the first element. The length is specified
as a 32-bit integer.
• GetLength() : Gets a 32-bit integer that represents the number of elements in the specified
dimension of the Array.
• GetLowerBound() : Gets the lower bound of the specified dimension in the Array.
• GetType() : Gets the Type of the current instance. (Inherited from Object.)
• GetUpperBound (): Gets the upper bound of the specified dimension in the Array.
• IndexOf(Array, Object) : Searches for the specified object and returns the index of the first
occurrence within the entire one-dimensional Array.
• Reverse(Array ) : Reverses the sequence of the elements in the entire one-dimensional Array.

• Sort(Array) : Sorts the elements in an entire one-dimensional Array.


• ToString() : Returns a string that represents the current object.

Strings
 Strings are used for storing text.
 A string variable contains a collection of characters surrounded by double quotes
Syntax: string greeting = "Hello”;
Example:
using System;
class StrProg

37
{
static void Main(){
string greeting = "Hello";
Console.WriteLine(greeting);
}
}

Types of strings

There are three types of string in C#:


1) Immutable strings
2) Mutable strings
3) Regular Expression

The immutable strings are those which can‘t be modified once objects are created and mutable
strings are modifiable. C# also supports a feature of regular expression that can be used for
complex strings manipulations and pattern matching
Immutable strings
Once object created it is immutable (can’t change).Immutable strings are created using string
object.
Example program for immutable strings
using System:
namespace Prog
{
Class P1
[
static void main()
{
string userstring=”C#”;
userstring+=”Programming”;
userstring+=”language”;
Console.WriteLine(userstring);
}
}
}

String handling mechanism


We can create immutable strings using string or String objects in a some techniques to handling the
immutable string.
Assigning String:
string s1 = "Welcome";
Copying String:
string s2 = s1;
or
string s2 = string.Copy(s1);
Concatenating Strings
string s3 = s1 + s2;
or
string s3 = string.Concat(s1,s2)

38
Inserting String
string s1 =" Wel";
string s1.insert(3,"come")
Comparing Strings
string. Compare(s1,s2);

 If s1 is equal to s2 it will return zero.


 If s1 is greater than s2 it will return positive integer (1).
 If s1 is less than s2 it will return negative integer(-1)

bool a = s2.Equals(s1);
bool b = string.Equal(s1,s2);

if(s1==s2)
Console.WriteLine(“both are equal”);

Mutable String
 Mutable strings are those strings, which can be modify dynamically. This type of strings are
created using StringBuilder class.
 It does not create unnessasary string objects
For Example:
StringBuilder s1 = new StringBuilder(“Welcome”);
StringBuilder s2 = new StringBuilder( );

Example program for mutable strings


using System;
using System.Text;
namespace Prog
{
Class P1
{
static void main()
{
StringBuilder userstring=new StringBuilder(”C#”);
userstring.Append(”Programming”);
userstring.Append(”language”);
Console.WriteLine(userstring.ToString());
}
}
}

The StringBuilder class supports many methods that are useful for manipulating dynamic
strings. Some of the most common methods are listed below

39
Example:
using System.Text; //For using StringBuilder
using System;
class StrMethod
{
public static void Main( )
{
StringBuilder s = new StringBuilder("C");
Console.WriteLine(" Stored String is :"+ s);
Console.WriteLine("Length of string is :"+s.Length);
s.Append("Sharp ");
Console.WriteLine( "After Append String is :"+ s);
Console.WriteLine("Length of string is :"+s.Length);
s.Insert(7,"Language");
Console.WriteLine("After Insertion String is:"+ s);
Console.WriteLine("Length of string is :"+s.Length);
int n = s.Length;
s[n] = "!";
Console.WriteLine(" At Last String is :"+ s);
}
}

OUTPUT:
Stored String is : C
Length of String is : 1
After Append string is : CSharp
After Insertion String is : CSharp Language
At Last String is : CSharp Language!

40
Regular Expression
In C#, Regular Expression is used for the parsing and validation of the given text to match with the
defined pattern (for example, an email address). The pattern can contain operators, characters literals,
or constructs.
Regex Class
Regex class shows the regular expression engine in the .NET Framework. Regex class is used to parse a
large amount of text for finding the specific character pattern. We can use the Regex class for the
extraction, editing, for the replacement, or to delete the text of the substring.
Example: // Create a pattern for the word that starts with letter "M"
string pattern = @"\b[M]\w+";
// Create a Regex
Regex rgex = new Regex (pattern);
System.Text.RegularExpressions namespace contains the Regex class.
Program:
using System;
using System.Text; //for StringBuilder class
using System.Text.RegularExpressions; //for Regex class

Program:
Class RegexTest
{
public static void Main()
{
string str;
str = "Amar, Akbar, Antony are friends!";
Regex reg = new Regex ("|, "); StringBuilder sb = new StringBuilder();
int count = 1;

foreach(string sub in reg.Split(str))


{
sb.AppendFormat("{0}: {1}\n", count++, sub);
}
Console.WriteLine(sb);
}
}
Structures and Enumerations
In C#, a structure is a value type data type. It helps you to make a single variable hold related data of
various data types. The struct keyword is used for creating a structure.
Syntax: Defining a struct
Access_Modifier struct structure_name
{
//Methods/Fields
}
Assigning values to members:
We can assign values to any data fields using (.) dot operator.
Person P1; // Declare P1 of type Person
P1.Name = "Keshav Gupta";
P1.Age = 21;

41
Program for Structure
using System;
namespace ConsoleApplication {
// Defining structure
public struct Person
{
public string Name;
public int Age;
}
class StruExample
{
static void Main()
{
Person P1; // Declare P1 of type Person
P1.Name = "Keshav Gupta";
P1.Age = 21;
Console.WriteLine(“Name:”+P1.Name);
Console.WriteLine(“Age:”+P1.Age);
}
}
}

In the above code, a structure with name “Person” is created with data members Name, Age in the main
method, P1 of structure type Person is created. Now, P1 can access its data members with the help of .(
dot ) Operator.

Copying Structure
Copy Structure: In C#, user can copy one structure object into another one using ‘=’ (Assignment)
operator
Syntax: Structure_object_destination = structure_object_source;
P2=P1
Example Program: (Refer above Example)
using System;
namespace ConsoleApplication {
// Defining structure
public struct Person
{
public string Name;
public int Age;
}
class StruExample
{
static void Main()
{
Person P1; // Declare P1 of type Person
P1.Name = "Keshav Gupta";
P1.Age = 21;
Person P2
P2=P1
Console.WriteLine(“Name:”+P1.Name);
Console.WriteLine(“Age:”+P1.Age);
}
}
}

42
Person P2;
// Copying the values of P1 into P2

P2 = P1;
Console.WriteLine("Name: " +P2.Name);
Console.WriteLine("Age: " +P2.Age);

Nesting Structure
C# allows the declaration of one structure into another structure and this concept is termed as the
nesting of the structure.
public struct Address
{
// data member of Address structure
public string City;
public string State;
}
// Another structure

struct Person
{
// data member of Person structure
public string Name;
public int Age;
}

Example Program:
using System;
namespace ConsoleApplication
{
public struct Address
{
public string City;
public string State;
}
struct Person
{
public string Name;
public int Age;
public Address A1;
}
class StrcExample {
static void Main()

{
Person p1;
p1.Name = "aaaa";
p1.Age = 12;
p1.A1.City = "Mysuru_City";
p1.A1.State = “Karnataka State";
Console.WriteLine("Name: " +p1.Name);
Console.WriteLine("Age: " +p1.Age);
Console.WriteLine("City: " +p1.A1.City);
Console.WriteLine("State: " +p1.A1.State);
}

43
}
}

Struct with Methods


We can also assign values to the data members using methods(constructor).Constructor is a method
which is used to set values of data members at the time of declaration.

struct Number
{
int number; //data member
public Number(int value) //constructor
{
Number=value;
}
}

Struct vs Classes
Structure Class
Value Type Reference type
Copies the value Copies the reference
Parameterless Constructors not Allowed Allowed
Inheritance not supported Always supported

Enumerations
An enumeration is a set of named integer constants. An enumerated type is declared using the enum
keyword. C# enumerations are value data type. In other words, enumeration contains its own values
and cannot inherit or cannot pass inheritance. It is used to store a set of named constants such as
season, days, month, size etc. The enum constants are also known as enumerators
Declaring enum Variable
Syntax:
enum <enum_name>
{
enumeration list
};

Initialization of enum variables


The default value of first enum member is set to 0 and it increases by 1 for the further data members of
enum. However, the user can also change these default value.
Example:
Enum Days
{
Sun=0
Mon=1
Tue=2
Wed=3
Thu=4
Fri=5
Sat=6
}

Example Program:
using System;
namespace EnumApplication {

44
class EnumProgram {
enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat };
static void Main()
{
int WeekdayStart = (int)Days.Mon;
int WeekdayEnd = (int)Days.Fri;
Console.WriteLine("Monday: ", WeekdayStart);
Console.WriteLine("Friday: ", WeekdayEnd);
OUTPUT:
Console.ReadKey(); Monday:1
} Friday:5
}
}

Type Conversion/Enum type casting:


Enum types can be converted to their base type(int type) and back again with and explicit conversion
using a cast.
Syntax: enum values
{
Value 0
Value 1
Value 2
}
values u1=(values)1;
int a=(int) u1;

Example for above program


using System;
public class Program
{
enum WeekDays
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}

public static void Main()

{
Console.WriteLine(WeekDays.Friday);
int day = (int) WeekDays.Friday;
Console.WriteLine(day);

var wd = (WeekDays)5;
Console.WriteLine(wd);
}
}

45
UNIT-2
OOPS With C#
 Classes, Objects, Inheritance, Polymorphism, Interfaces, Operator Overloading Delegates,
Events, Errors and Exceptions.

Classes and Objects

A class is a user-defined blueprint or prototype from which objects are created. Basically, a class
combines the fields and methods (member function which defines actions) into a single unit. In C#,
classes support polymorphism, inheritance and also provide the concept of derived classes and base
classes. It can have fields, methods, constructors etc.

Declaration of Classes
Class is an user-defined data type. To create a class, you start with the class keyword followed
by a name and its body delimited by curly brackets.
Syntax:
class classname
{
// class-body
}
The class-body contains the member data and member function of the class.

Members of Class
Class is a mechanism to implement the encapsulation, it bind the data and a function in a
single unit. Therefore data and functions are the members of class, which is known as member
data and member function.
Example of full class :
class Circle
{
double radius;
public void get_radius(double r)
{
radius = r;
}
public double area()
{
return ( 3.14 * r *r);
}
}
Member Access Modifiers/visibility control:
Access modifiers provide the accessibility control for the members of classes to outside the
class. They also provide the concept of data hiding. There are five member access modifiers
provided by the C# Language. By default all member of class have private accessibility.

46
Example:
class Demo
{
public int a;
internal int x;
protected double d;
float m; // private by default
}

Objects
 Object is an instance of a class. All the members of the class can be accessed through objects. In
C#, Object is a real world entity, for example, chair, car, pen, mobile, laptop etc.
 In other words, object is an entity that has state and behaviour. Here, state means data and
behaviour means functionality.
 Object is a runtime entity, it is created at runtime.
Example:
Student s1 = new Student();//creating an object of Student
In this example, Student is the type and s1 is the reference variable that refers to the instance of
Student class. The new keyword allocates memory at runtime.

C# Constructor
In C#, constructor is a special method which is invoked automatically at the time of object creation. It is
used to initialize the data members of new object generally. The constructor in C# has the same name as
class name.
 A constructor cannot be abstract, final, and Synchronized.
 A constructor doesn’t have any return type, not even void
Syntax:
class Car {
// constructor
Car()
{
//code
}
}
Once we create a constructor, we can call it using the new keyword.
new Car();

There can be three types of constructors in C#.


 Default constructor
 Parameterized constructor
 Static Constructor

Default constructor

47
 A constructor which has no argument or constructor without any parameters is called a default
constructor. It is invoked at the time of creating object.
 The drawback of a default constructor is that every instance of the class will be initialized to the
same values and it is not possible to initialize each instance of the class to different values.
Example:
using System;
public class Employee
{
public Employee()
{
Console.WriteLine("Default Constructor Invoked");
}
public static void Main(string[] args)
{
Employee e1 = new Employee();
}
}
Parameterized Constructor
A constructor which has parameters is called parameterized constructor. It is used to provide different
values to distinct objects. . It can initialize each instance of the class to different values.
Example:
using System;
public class Employee
{
public int id;
public String name;
public float salary;
public Employee(int i, String n,float s)
{
id = i;
name = n;
salary = s;

}
public void display()
{
Console.WriteLine(id + " " + name+" "+salary);
}
}
class TestEmployee{
public static void Main(string[] args)
{
Employee e1 = new Employee(101, "Sonoo", 890000.00);
Employee e2 = new Employee(102, "Mahesh", 490000.00);
e1.display();
e2.display();

}
}
Static constructor
C# static constructor is used to initialize static fields. It can also be used to perform any action that is to
be performed only once. It is invoked automatically before first instance is created or any static member
is referenced.
 C# static constructor cannot have any modifier or parameter.
 C# static constructor is invoked implicitly. It can't be called explicitly.
Example:

48
using System;
class Account
{
public int id;
public String name;
public static float Interest;
public Account(int i, String n)
{
id = i;
name = n;
}
static Account()
{
Interest = 9.5;
}
public void display()
{
Console.WriteLine(id + " " + name+" "+Interest);
}
}
class TestEmployee{
public static void Main(string[] args)
{
Account a1 = new Account(101, "Sonoo");
Account a2 = new Account(102, "Mahesh");
a1.display();
a2.display();
}
}

Destructor
A destructor works opposite to constructor, It destructs the objects of classes. It can be defined only
once in a class. Like constructors, it is invoked automatically. ~ Symbol is used to destruct the objects.
Example:
public class Employee
{
public Employee()
{
Console.WriteLine("Constructor Invoked");
}
~Employee()
{
Console.WriteLine("Destructor Invoked");
}
}
class TestEmployee{
public static void Main(string[] args)
{
Employee e1 = new Employee();
}
}

Constructor Overloading

49
Constructor Overloading is a technique to define multiple constructors within a class with different sets
of parameters to achieve polymorphism. We can overload constructors in C# just like methods. We can
do so by changing the signatures by using a different number, or type of parameters.
Syntax:
class Car {
Car(string brand) {
...
}

Car(int price) {
...
}
}
Example:
using System;
namespace ConstructorOverload {
class Car {
Car(string brand) // constructor with string parameter
{
Console.WriteLine("Brand: " + brand);
}
Car(int price) { // constructor with int parameter
Console.WriteLine("Price: " + price);
}
static void Main(string[] args)
{
Car car = new Car("Lamborghini");
Console.WriteLine();
Car car2 =new Car(50000);
}
}

Indexers in C#
An indexer allows an object to be indexed such as an array. When you define an indexer for a class, this
class behaves similar to array. You can then access the instance of this class using the array access
operator ([ ]).

Syntax
A one dimensional indexer has the following syntax −
element-type this[int index] {

get {
// body
}

set {
//body
}
}
Example Program
using System;
class Test
{
string[] names=new string[4];
public string this[int i]

50
{
get
{
return names[i];
}
set{
names[i]=value;
}
static void Main()
Test obj=new Test();
obj[0]=”car”;
obj[1]=”omni”;
obj[2]=”scooty”;
for(int i=0;i<3;i++)
Console.WriteLine(obj[i]);
}
}
Overloaded Indexers:
Indexers can be overloaded. Indexers can also be declared with multiple parameters and each
parameter may be a different type. It is not necessary that the indexers have to be integers. C# allows
indexes to be of other types.
Example:
public string this[int i]
{
get
{
return names[i];
}
set{
names[i]=value;
}
public string this[double i]
{
get
{
return names[i];
}
set{
names[i]=value;
}

Inheritance
In C#, inheritance is a process in which one object acquires all the properties and behaviours of its
parent object automatically. In such way, you can reuse, extend or modify the attributes and behaviours
which is defined in other class. Code reusability: Now you can reuse the members of your parent class.
So, there is no need to define the member again. So less code is required in the class.
 Derived Class (child) - the class that inherits from another class
 Base Class (parent) - the class being inherited from.

Syntax:
class derived-class : base-class
{
// methods and fields
.
.

51
}

Types of Inheritance in C#
Single Inheritance: In single inheritance, subclasses inherit the features of one superclass. In image
below, the class A serves as a base class for the derived class B.
Syntax:
class sub_class_name : base_class_name
{
//body of subclass
};

Example Program:
using System;

namespace InheritanceEg
{
public class ParentClass
{
public void printParent()
{
Console.WriteLine("This is Parent Class");
}
}

public class ChildClass: ParentClass


{
public void printChild()
{
Console.WriteLine("This is Child Class");
}
}

public class Program


{
public static void Main(string[] args)
{
ChildClass obj = new ChildClass();
obj.printParent();
obj.printChild();
}
}
}

Multilevel Inheritance: In Multilevel Inheritance, a derived class will be inheriting a base class and as
well as the derived class also act as the base class to other class. In below image, class A serves as a base
class for the derived class B, which in turn serves as a base class for the derived class C.

52
Example Program:
using System;

namespace InheritanceEg
{
public class Animal
{
public void sleep()
{
Console.WriteLine("Animal sleeps");
}
}

public class Dog: Animal //Inheriting Animal


{
public void sound()
{
Console.WriteLine("Dog barks");
}
}

public class Puppy: Dog //Inheriting Dog


{
public void weep()
{
Console.WriteLine("Puppy weeps");
}
}

public class Program


{
public static void Main(string[] args)
{
Puppy p = new Puppy();

p.sleep();
p.sound();
p.weep();

}
}
}
Hierarchical Inheritance: In Hierarchical Inheritance, one class serves as a superclass (base class) for
more than one subclass. In below image, class A serves as a base class for the derived class B, C, and D.
Syntax:
class One

53
{
// Class One members
}
class Two : One
{
// Class Two members.
}
class Three : One
{
// Class Three members
}

Example Program:
using System;

namespace InheritanceEg
{
public class ParentClass
{
public void printParent()
{
Console.WriteLine("This is Parent Class");
}
}

public class Son: ParentClass //Inheriting ParentClass


{
public void printSon()
{
Console.WriteLine("This is Son's Class");
}
}
public class Daughter: ParentClass //Inheriting ParentClass
{
public void printDaughter()
{
Console.WriteLine("This is Daughter's Class");
}
}
//Main Class
public class Program
{
public static void Main(string[] args)
{
Son s = new Son();
Daughter d = new Daughter();

54
s.printSon();
s.printParent();

d.printDaughter();
d.printParent();

}
}
}

Multiple Inheritance(Through Interfaces):In Multiple inheritance, one class can have more than one
superclass and inherit features from all parent classes. Please note that C# does not support multiple
inheritance with classes. In C#, we can achieve multiple inheritance only through Interfaces.

Example Program:
using System;

namespace InheritanceEg
{
interface Dog
{
void dogFunc();
}

interface Cat
{
void catFunc();
}

public class Animal: Dog, Cat //Inheriting Dog and Cat interface
{
public void dogFunc()
{
Console.WriteLine("I am a Dog");
}

public void catFunc()


{
Console.WriteLine("I am A Cat");
}

public void animalFunc()


{
Console.WriteLine("All are Animals");
}
}

55
public class Program
{
public static void Main(string[] args)
{
Animal obj = new Animal();

obj.animalFunc();
obj.dogFunc();
obj.catFunc();

}
}
}
Hybrid Inheritance(Through Interfaces): It is a mix of two or more of the above types of inheritance.
Since C# doesn’t support multiple inheritance with classes, the hybrid inheritance is also not possible
with classes. In C#, we can achieve hybrid inheritance only through Interfaces.

Abstract Classes
 An abstract class can have both abstract methods (method without body) and non-abstract
methods (method with the body).
 As we cannot create objects of an abstract class, we must create a derived class from it. So that
we can access members of the abstract class using the object of the derived class.
 The abstract is a modifier and when used to declare a class indicates that class cannot be
instantiated. Only derived class can be instantiated.

Example:
abstract class Base
{
…….
}
class Derived: Base
{
…….
}
Derived d1

Abstract Methods
 A method that does not have a body is known as an abstract method. We use the abstract
keyword to create abstract methods.
Example:
o public abstract void Draw(int x, int y)

 It cannot have implementation.


 It can be declared only in abstract classes.

56
 Its implementation is provided by derived classes by overriding the method.

Sealed Classes: Preventing Inheritance


Sometimes, We may not like to prevent a class being further subclassed for security reasons. A
class that cannot subclassed further is called sealed class. This is achieved by using the modifier
sealed.

Example:
sealed class Aclass
{
………
}
sealed class Bclass: Aclass
{
………..
}
Any attempt to inherit these classes will cause an error and the compiler will not allow it.

Sealed Methods
o The method is said to be sealed if a derived class cannot override this method,
o A sealed method is used to override and inherited virtual method with the same signatures.
Example: The sealed method Fun()overrides the virtual method Fun()defined in class A. Any
derived class cannot further override the method Fun().
class A
{
public virtual void Fun()
{
……..
}
}
class B:A
{
public sealed override void Fun()
{
…….
}
}

Polymorphism

The term "Polymorphism" is the combination of "poly" + "morphs" which means many forms.
Polymorphism provides the ability to a class to have multiple implementations with the same name.

There are two types of polymorphism in C#:

 Static / Compile Time Polymorphism.


 Dynamic / Runtime Polymorphism.

57
Compile time polymorphism is achieved by method overloading and operator overloading in C#. It
is also known as static binding or early binding. Runtime polymorphism in achieved by method
overriding which is also known as dynamic binding or late binding.

Method Overriding
 If derived class defines same method as defined in its base class, it is known as method
overriding in C#. It is used to achieve runtime polymorphism. It enables you to provide specific
implementation of the method which is already provided by its base class.
 In simple words, Overriding is a feature that allows a subclass or child class to provide a specific
implementation of a method that is already provided by one of its super-classes or parent
classes.
 To perform method overriding in C#, you need to use virtual keyword with base class method
and override keyword with derived class method.
Example:
using System;
class Base
{
public virtual void display()
{
Console.WriteLine(“Base class display:”);
}
public override void display ()
{
Console.WriteLine(“Derived class display:”);
}
class Derived: Base
{
static void Main()
{
Derived obj=new Derived();
obj. display();
}
}
}

Method Hiding
C# also provides a concept to hide the methods of the base class from derived class, this concept is
known as Method Hiding. It is also known as Method Shadowing. In method hiding, you can hide the
implementation of the methods of a base class from the derived class using the new keyword.

Example:[Refer method Overriding program]

58
class Base
{
public void display()
{
Console.WriteLine(“Base class display:”);
}
public new void display ()
{
Console.WriteLine(“Derived class display:”);
}
class Derived: Base
{
static void Main()
{
Derived obj=new Derived();
obj. display();
}
}
}

C# Interface
Interface in C# is a blueprint of a class. It is like abstract class because all the methods which are
declared inside the interface are abstract methods. It cannot have method body and cannot be
instantiated. But interfaces will contain only the declaration of the members. The implementation of the
interface’s members will be given by class who implements the interface implicitly or explicitly.
 Multiple inheritance is possible with the help of Interfaces but not with classes
 Interfaces specify what a class must do and not how.

Syntax
interface <interface_name >
{
// declare methods
}

Syntax for Implementing Interface:


class class_name : interface_name

Multiple Interface
C# allows the implementation of multiple interfaces with the same method name. To understand how to
implement multiple interfaces with the same method name.
Syntax:
class Rectangle : Polygon, Color
{
public void calArea(int a, int b)
{
………………
}

Example for Interface/Multiple Interface:

using System;
interface Polygon {
void calArea(int a, int b);
}

59
interface Color //another interface
{
void getColor();
}
// implements two interface
class Rectangle : Polygon, Color
{
public void calArea(int a, int b)
{
int area = a * b;
Console.WriteLine("Area of Rectangle: " + area);
}
public void getColor()
{
Console.WriteLine("Red Rectangle");
}
}
class Program {
static void Main (string [] args) {
Rectangle r1 = new Rectangle();
r1.calculateArea(100, 200);
r1.getColor();
}
}
}

Nested Classes in C#
 A class is a user-defined blueprint or prototype from which objects are created. C#, a user is
allowed to define a class within another class. Such types of classes are known as nested class.
 This feature enables the user to logically group classes that are only used in one place, thus this
increases the use of encapsulation, and create more readable and maintainable code.

Syntax:
class Outer_class
{
// Code..
class Inner_class
{
// Code..
}
}

Operator Overloading
Operator overloading gives the ability to use the same operator to do various operations. It provides
additional capabilities to C# operators when they are applied to user-defined data types. An operator
can be overloaded by defining a function to it. The function of the operator is declared by using the
operator keyword.
An operator can be overloaded by defining a function to it. The function of the operator is declared by
using the operator keyword.

Syntax:
access specifier className operator Operator_symbol (parameters)
{
// Code

60
}

Operators Description
+, -, !, ~, ++, – – unary operators take one operand and can be overloaded.
+, -, *, /, % Binary operators take two operands and can be overloaded.
==, !=, = Comparison operators can be overloaded.
&&, || Conditional logical operators cannot be overloaded directly
+=, -+, *=, /=, %=, = Assignment operators cannot be overloaded.

Unary Operator Overloading


Here, the return type can be anything, but it should not be void for the operators like +,-, ~ and .(dot).
The return type of this operator should be either an integer or a Boolean type
The following syntax shows the use of Unary operator –
operator (object);
here, operator is a symbol that denotes a unary operator.
operator a;

Overloading Binary Operators


Binary Operators will work with two Operands. Examples of binary operators include the Arithmetic
Operators (+, -, *, /, %), Arithmetic Assignment operators (+=, -+, *=, /+, %=) and Relational Operators.
Syntax:
operator operator (object1, object2);
Here, second "operator" is a symbol that denotes a binary operator.
operator + (a, b)
Example Program:
using System;
namespace BinaryOverload {
class Calculator {
int number;
public Calculator() {
}
public Calculator(int n)
{
number = n;
}
// Overloading of Binary "+" operator
public static Calculator operator + (Calculator Calc1, Calculator Calc2)
{
Calculator Calc3 = new Calculator(0);
Calc3.number = Calc2.number + Calc1.number;
return Calc3;
}
public void display() {
Console.WriteLine(number);
}
}
class CalNum {
static void Main(string[] args) {
Calculator num1 = new Calculator(200);
Calculator num2 = new Calculator(40);
Calculator num3 = new Calculator();
num3 = num1 + num2;
num1.display(); // Displays 200
num2.display(); // Displays 40

61
num3.display(); // Displays 240
}
}

Delegates in C#
C# delegates are similar to pointers to functions, in C or C++. A delegate is a reference type variable that
holds the reference to a method.it is a type that represents references to methods with a particular
parameter list and return type and then calls the method in a program for execution when it is needed.
 Delegates are especially used for implementing events and the call-back methods.
 It provides a good way to encapsulate the methods.
 These are the type-safe pointer of any method.
 All delegates are implicitly derived from the System.Delegate class.

Syntax for delegate declaration is –


Delegate type can be declared using the delegate keyword.

delegate <return type> <delegate-name> <parameter list>

Instantiating Delegates
 Once a delegate type is declared, a delegate object must be created with the new keyword and
be associated with a particular method.
 The parameters passed to the delegate by the caller are passed to the method, and the return
value, if any, from the method, is returned to the caller by the delegate. This is known as
invoking the delegate.

Syntax:
[delegate_name] [instance_name] = new [delegate_name](calling_method_name);

Example program for Delegates:


using System;
delegate int Calculator(int n);//declaring delegate
public class DelegateExample
{
static int number = 100;
public static int add(int n)
{
number = number + n;
return number;
}
public static int mul(int n)
{
number = number * n;
return number;
}
public static int getNumber()
{
return number;
}
public static void Main(string[] args)
{
Calculator c1 = new Calculator(add);//instantiating delegate
Calculator c2 = new Calculator(mul);
C2+=mul; //multicast delegate
c1(20);//calling method using delegate

62
Console.WriteLine("After c1 delegate, Number is: " + getNumber());
c2(3);
Console.WriteLine("After c2 delegate, Number is: " + getNumber());
}
}

Multicasting Delegates
A delegate that holds a reference to more than one method is called multicasting delegate.
Multicast Delegates are also known as Combinable Delegates,
The delegate can point to multiple methods. A delegate that points multiple methods is called a
multicast delegate. The "+" or "+=" operator adds a function to the invocation list, and the "-" and "-="
operator removes it.
Example:[Refer same above example program of delegates]

Events in C#
Events are user actions such as key press, clicks, mouse movements, etc., or some occurrence such as
system generated notifications. Applications need to respond to events when they occur.
The events are declared and raised in a class and associated with the event handlers using delegates
within the same class or some other class. The class containing the event is used to publish the event.
This is called the publisher class. Some other class that accepts this event is called the subscriber class.
Events use the publisher-subscriber model.

 A publisher is an object that contains the definition of the event and the delegate. The event-
delegate association is also defined in this object. A publisher class object invokes the event and
it is notified to other objects.

 A subscriber is an object that accepts the event and provides an event handler. The delegate in
the publisher class invokes the method (event handler) of the subscriber class.

Example Program for events:


class Program
{
public static void Main()
{
ProcessBusinessLogic bl = new ProcessBusinessLogic();
bl.ProcessCompleted += bl_ProcessCompleted; // register with an event

63
bl.StartProcess();
}

// event handler-subscriber class


public static void bl_ProcessCompleted()
{
Console.WriteLine("Process Completed!");
}
}
public delegate void notify();
public class ProcessBusinessLogic
{
public event notify ProcessCompleted() //publisher class
public void StartProcess()
{
Console.WriteLine("Process Started!");
OnProcessCompleted()
}

protected virtual void OnProcessCompleted()


{
ProcessCompleted?invoke()
}
}
}

Errors
Errors refer to the mistake or faults which occur during program development or execution. If you don't
find them and correct them, they cause a program to produce wrong results.
Errors may be broadly classified into two categories:
 Compile time errors
 Runtime errors
Compile-time errors are the errors that occurred when we write the wrong syntax.
Most common Compile time errors are:
 Missing semicolons.
 Missing brackets in classes and methods.
 Misspelling of identifiers and keywords.
 Missing double quotes.
 Use of undeclared variables.
Runtime-time errors are sometimes program may successfully compile but not run properly. Such
program may produce wrong results due to wrong logic or may terminate due to errors.
Most common Runtime-errors are:
 Dividing an integer by zero.
 Accessing an element that is out of the bounds of an array.
 Trying to store a value into an array of an incompatible class or type.
 Attempting to use negative size for an array.
 Converting invalid string to number vice versa.

Exceptions in C#
An exception is a problem that arises during the execution of a program. A C# exception is a response to
an exceptional circumstance that arises while a program is running, such as an attempt to divide by
zero.
Exception Handling Mechanisms:
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.

64
try − A try block identifies a block of code for which particular exceptions is activated. It is 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:
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
}

Example Program for Exceptions:


using System;
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: ", e);
}
finally
{
Console.WriteLine("Result: {0}", result);
}
}
static void Main(string[] args)
{
DivNumbers d = new DivNumbers();
d.division(25, 0);
Console.ReadKey();
}
}

65
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 System.ApplicationException class supports exceptions generated by application programs. Hence


the exceptions defined by the programmers should derive from this class.

The System.SystemException class is the base class for all predefined system exception.
Exception Class & Description
o
 System.IO.IOException
Handles I/O errors.

 System.IndexOutOfRangeException
Handles errors generated when a method refers to an array index out of range.

 System.ArrayTypeMismatchException
Handles errors generated when type is mismatched with the array type.

 System.NullReferenceException
Handles errors generated from referencing a null object.

 System.DivideByZeroException
Handles errors generated from dividing a dividend with zero.

 System.InvalidCastException
Handles errors generated during typecasting.

 System.OutOfMemoryException
Handles errors generated from insufficient free memory.

 System.StackOverflowException
Handles errors generated from stack overflow.

Exception hierarchy
The class at the top of the exception class hierarchy is the Throwable class, which is a direct subclass of
the Object class. Throwable has two direct subclasses - Exception and Error. The Exception class is used
for exception conditions that the application may need to handle.

66
Throwing Objects/Exceptions
You can throw an object if it is either directly or indirectly derived from the System.Exception class. You
can use a throw statement in the catch block to throw the present object as −

Catch(Exception e) {
...
Throw e
}

Custom Exceptions /User defined Exceptions:


C# allows us to create user-defined or custom exception. It is used to make the meaningful exception.
To do this, we need to inherit Exception class.
Syntax:
throw new throwable_subclass
Example:
throw new ArithmeticException();
Example Program:
class DivByZero : Exception {
public DivByZero()
{
Console.Write("Exception has occurred : ");
}
}
class Program
{
public double DivisionOperation(double numerator,double denominator){
if (denominator == 0)
throw new DivByZero();
return numerator / denominator;]
}
static void Main(string[] args)
{

67
Program obj = new Program();
double num = 9, den = 0, quotient
try
{
quotient = obj.DivisionOperation(num, den);
Console.WriteLine("Quotient = {0}", quotient);
}
catch (Exception e) {
Console.Write(e.Message);
}
}
}

Nested try block


In C#, the nesting of the try & catch block is allowed. The nesting of try block means one try block can
be nested into another try block. The various programmer uses the outer try block to handling serious
exceptions, whereas the inner block for handling normal exceptions.
Syntax:
// outer try block
try
{

// inner try block


try
{
// code...
}

// inner catch block


catch
{
// code...
}
}

// outer catch block


catch
{
// code...
}

C# Checked and Unchecked operator


Stack overflows are usual problems during arithmetic operations. C# supports two operators checked
and unchecked which can be used for checking or unchecking stack overflows during program
execution. If and operation is checked, then an exception will be thrown if overflow occurs. If it is not
checked, no exception will be raised but will produce a wrong or truncated results.
Example:
int a=2000000
int b=3000000
try
{
int m=checked(a*b);
}
catch (OverflowException e)

68
{
Console.WriteLine(e);}

If we want to uncheck
int a=2000000
int b=3000000
try
{
int n=unchecked(a*b)
}
catch (OverflowException e)
{
Console.WriteLine(e);}

Multithreading
C# Multithreading
Multithreading in C# is a process in which multiple threads work simultaneously. It is a process to
achieve multitasking. It saves time because multiple tasks are being executed at a time. To create
multithreaded application in C#, we need to use System.Threading namespace.
Threads are lightweight processes. One common example of use of thread is implementation of
concurrent programming by modern operating systems. Use of threads saves wastage of CPU cycle and
increase efficiency of an application.

The Unstarted State − It is the situation when the instance of the thread is created but the Start method
is not called.
The Ready State − It is the situation when the thread is ready to run and waiting CPU cycle.
The Not Runnable State − A thread is not executable, when
The Dead State − It is the situation when the thread completes execution or is aborted.

Introduction to VB.NET

.NET Framework

.NET is a framework to develop software applications. It is designed and developed by Microsoft


and the first beta version released in 2000.
It is used to develop applications for web, Windows, phone.
This framework contains a large number of class libraries known as Framework Class Library
(FCL). The software programs written in .NET are executed in the execution environment, which
is called CLR (Common Language Runtime). These are the core and essential parts of the .NET
framework

The .NET Framework is composed of four main components:

 Common Language Runtime (CLR)


 Framework Class Library (FCL),
 Core Languages (WinForms, ASP.NET, and ADO.NET), and
 Other Modules (WCF, WPF, WF, Card Space, LINQ, Entity Framework, Parallel LINQ, Task
Parallel Library, etc.)

69
The .NET Framework class library facilitates types (CTS) that are common to all
.NET languages.

NET Framework Architecture has languages at the top such as VB .NET C#, VJ#,
VC++ .NET; developers can develop (using any of above languages) applications
such as Windows Forms, Web Form, Windows Services and XML Web Services.
Bottom two layers consist of .NET Framework class library and Common Language
Runtime.

CLR (Common Language Runtime)


It is a program execution engine that loads and executes the program. It converts the program into
native code. It acts as an interface between the framework and operating system.

FCL (Framework Class Library)


It is a standard library that is a collection of thousands of classes and used to build an application. The
BCL (Base Class Library) is the core of the FCL and provides basic functionalities.

VB.NET Introduction
1. VB.NET is a simple, multi-paradigm object-oriented programming language designed to create a
wide range of Windows, Web, and mobile applications built on the .NET Framework.
2. The VB.NET stands for Visual Basic. Network Enabled Technologies. It is a simple, high-level,
object-oriented programming language developed by Microsoft in 2002.
3. Furthermore, it supports the OOPs concept, such as abstraction, encapsulation, inheritance, and
polymorphism. It is not a case sensitive language, whereas, C++, Java, and C# are case sensitive
language.

Features of VB.NET

 It is an object-oriented programming language that follows various oops concepts such as


abstraction, encapsulation, inheritance, and many more. It means that everything in VB.NET
programming will be treated as an object.
 This language is used to design user interfaces for window, mobile, and web-based applications.

70
 It supports a rapid application development tool kit. In which a developer does not need to
write all the codes as it can get various code automatically from its libraries. For example, when
we create a form in Visual basic.net, it automatically calls events of various form in that class.
 It is not a case sensitive language like other languages such as C++, java, etc.
 It supports Boolean condition for decision making in programming.
 It also supports the multithreading concept, in which you can do multiple tasks at the same time.
 It provides simple events management in .NET application.
 A Window Form enables us to inherit all existing functionality of form that can be used to create
a new form. So, in this way, it reduced the code complexity.
 It uses an external object as a reference that can be used in a VB.NET application.
 Automatic initialized a garbage collection.
 It follows a structured and extensible programming language for error detection and recovery.
 Conditional compilation and easy to use generic classes.
 It is useful to develop web, window, and mobile applications.

Visual Basic.Net Program Structure

Module Module1
'This program will display Hello World
Sub Main() //MAIN METHOD
Console.WriteLine("Hello World") //DISPLAYS OUTPUT
Console.ReadKey()
End Sub //stops
End Module

 The First line has a Module declaration, the module Module1. VB.Net is completely object
oriented, so every program must contain a module of a class that contains the data and
procedures that your program uses.

 The next line defines the Main procedure, which is the entry point for all VB.Net programs. The
Main procedure states what the module or class will do when executed.

 Console.WriteLine("Hello World") WriteLine is a method that displays the output.

 The last line Console.ReadKey() is for the VS.NET Users. This will prevent the screen from
running and closing quickly when the program is launched from Visual Studio .NET.

Visual Basic IDE –(Integrated Development Environment)


Visual Basic is an event driven programming language. This means that code is executed as a response
to an event. IDE is the work setting to create Visual Basic applications. This helps to develop, run, test
and debug applications. Visual Basic provides a graphical environment in which the programmer can
visually design the forms and other controls that become the building block of the application.

IDE is a term commonly used in the programming world to describe the interface and environment that
we use to create our applications. It is called integrated, because we canaccess virtually all of the
development tools that we need from one screen, called aninterface

Visual Basic IDE is made up of a number of components. They are


●Menu Bar
●Tool Bar
●Tool Box

71
●Properties Window
●Form Designer
●Form Layout
●Solution Explorer

Creating shortcut to start VB.NET


Creating Shortcuts in VBNET WithOut Installers
If you are looking to add shortcuts in VBNET without installers, you use the ShellLink.cs available at
vbAccelerator. However, you need to add Windows Script Host Object Model reference.
 Right click on your project
 Click “Add Reference…”
 Select the “COM” tab on the left
 Search for Windows Script Host Object Model and add it as a
reference

Click the Windows key, and then browse to the Office program for
which you want to create a desktop shortcut.

 Right-click the program name or tile, and then select Open file location.

 Right-click the program name, and then click Send To > Desktop (Create shortcut).

 A shortcut for the program appears on your desktop

Desktop Shortcut Creation


A file-based object is basically anything inside a computer drive or directory, so a shortcut providing a
link to a file of any sort is a “File-based Shortcut”.

This code creates shortcut:


IWshShell wsh = new WshShellClass();
IWshShortcut shortcut = (IWshShortcut) wsh.CreateShortcut (shortcutpathfilename);
shortcut.TargetPath = targetdir;

Maneuverings the Toolbar/Working with Toolbar


In the standard tool bar frequently used buttons such as add-form, open project, save project etc.
The tool bar provides easy access to the menu bar commands that are used frequently. Toolbar control
is not available in Toolbox of Visual Studio 2010. ToolStrip control replaces Toolbar in Visual Studio
2010.A Toolbar control is a combination of Toolbar buttons where each button represents a function. A
Toolbar button can display an image, text or a combination of both. The button click event handler is
responsible for executing some code.

Adding toolbar into form


 To create a ToolStrip control at design-time, simply drag and drop a ToolStrip control from
Toolbox onto a Form.(see figure—01)
 A ToolStrip control is nothing but a container without adding its child controls. A ToolStrip
control is capable of hosting Button, Label, SplitButton, DropDownButton, Separator,
ComboBox, TextBox and ProgressBar controls.
 If you click on a little dropdown handle on a ToolStrip control in designer, you will see a list of
possible controls that can be added to a ToolStrip. To add a control, simply select that control
and it will be added to the ToolStrip control.

72
Adding buttons to toolbar and setting icons to buttons
 Now let's create a sample. We are going to add three Button controls, three separators and a
Label control.
 Now next we are going to set an icon for the Button controls by setting Image property of
Button.
 Once you click on the browse option to browse an image, Resource editor window pops up
where you can import an image. Click on Import button and browse an image file.
 We set three icons for all three buttons and the ToolStrip.

Writing button code:


Next step is to set the button click event handler. Just double click or use Events window and set click
event handlers for all three buttons.
Three button click event handlers look like the following where we set Text property of Label.
Now if you run the project and click on Buttons particular buttons performs following functions:
Button1Debug
Button2 Delete
Button3Save

Program
Public Class Form1
Private Sub toolStripButton1_Click(sender As System.Object, e As System.EventArgs)
ToolStripLabel1.Text = "Debug is clicked"
End Sub
Private Sub ToolStripButton2_Click(sender As System.Object, e As
System.EventArgs)
ToolStripLabel1.Text = "delete is clicked"
End Sub
Private Sub ToolStripButton3_Click(sender As System.Object, e As
System.EventArgs)
ToolStripLabel1.Text = "save is clicked"
End Sub
End Class

OUTPUT:(HERE BUTTON2 IS CLICKED):


AutoHide
Once the initial VB.NET screen appears, you’ll find the controls stored inside of the
toolbox on the left side of the screen. These are the objects you can place on a form.
Users interact with these objects.
The direction of the push pin on the toolbox's title bar dictates whether or not auto
hide is in effect. If the push pin is vertical, auto hide is turned off. This means that the
toolbox is always visible. If you click on the push pin, it will be displayed vertically.
At this point, auto hide is activated and moving your cursor off the toolbox will cause
it to collapse. It will only expand when your cursor is over the toolbox icon that appears docked against
the left corner of the window. Other windows also have autohide capabilities activated and deactivated
by clicking the window's respective push pin.

73
If push pin is vertical then
autohide is activated

ToolBox
Tool Box consists of all the controls essential for developing a VBapplication. Controls are elements that
provide the user interface. Controls are tools such as text box, command button, label and other objects
that can be dragged and drawn on a form to perform certain tasks according to the events associated.

Some tools of toolbax are listed below:

Label Displays a text that the user cannot modify.

Docking and Undocking


Docking of a control means docking it to one of the edges of its container. In docking, the control fills
certain area of the container completely. In simple terms, Docking a control fills a certain area of the
form. You can only dock to one side at a time, and the default is None which means control is undocked
and it can moved freely.
By default the dock property of the controls is selected to None. If you want to dock a control, click on
the control which you want to dock. Open Properties Window and select the Dock property. In the small
editor click the button that represents the edge of the form where you want to dock the control.

74
The Dock property of the Control class does this. The Dock property gets or sets which control borders
are docked to its parent control and determines how a control is resized with its parent.
Use the Visual Studio designer Properties window to set the docking mode of a control.

A control is docked by setting its Dock property.

 Select the control in the designer.


 In the Properties window, select the arrow to the right of the Dock property.
 Select the button that represents the edge of the container where you want to dock the control.
To fill the contents of the control's form or container control, press the center box. Press none to
disable docking.

Docking in code
Set the Dock property on a control. In this below code, a button is docked to the right side of its
container:
button1.Dock = DockStyle.Right;

DockPadding-The container (form, panel, or other type of container control) has a DockPadding
property, which allows it to specify a certain amount of padding between it and
docked controls. The padding values can be specified individually for the four sides of
the container, or an overall padding value that applies to all of the sides at once. If a
container has specified a DockPadding value of 10, for example, a control docked the left will be will be
positioned 10 pixels away from the left edge.

Undocking: If none option is selected then dock of a control is disabled means the control

Figure:

Control is docked to left

Forms
 A Form is used in VB.NET to create a form-based or window-based application. Using the form,
we can build a attractive user interface.
 It is like a container for holding different control that allows the user to interact with an
application.
 The controls are an object in a form such as buttons, Textboxes, Text area, labels, etc. to perform
some action. However, we can add any control to the runtime by creating an instance of it.
 A Form uses a System.Windows.Form namespace, and it has a wide family of controls that add
both forms and functions in a Window-based user interface.

Placing and Resizing the Windows


Let's start with creating a Window Forms Application by following the following steps in Microsoft
Visual Studio:
 Open Visual Studio.
 On the start window, choose Create a new project.

75
 On the Create a new project window, select the Windows Forms App (.NET Framework)
template for Visual Basic.
 Click OK
 Window Form gets placed.
Resizing the form

When a form is created, the size and location is initially set to a default value. The default size of a form
is generally a width and height of 800x500 pixels. The initial location, when the form is displayed,
depends on a few different settings.

1. After adding a new form to the project, the size of a form is set in two different ways. First, you
can set it is with the size grips in the designer. By dragging either the right edge, bottom edge, or
the corner, you can resize the form.

2. The second way you can resize the form while the designer is open, is through the properties
pane. Select the form, then find the Properties pane in Visual Studio. Scroll down to size and
expand it. You can set the Width and Height manually in Properties window.

Resize in code
Even though the designer sets the starting size of a form, you can resize it through code. For example, if
you have Form1 with a button on it, that when clicked invokes the Click event handler to resize the
form:
private void button1_Click(object sender, EventArgs e)
Size = new Size (250, 200);

Properties Window
1. This window (also known as the Properties Browser) displays all the properties of the
selected component and its settings.
2. A property is a piece of information that characterizes a control. It could be related to its
location or size. It could be its color, its identification, or any visual aspect that
gives it presence on the screen. The properties of an object can be changed either at
design time or at run time.
3. You can also manipulate these characteristics both at design and at run times. This means
that you can set some properties at design time and some others at run time.
4. To manipulate the properties of a control at design time, first click the desired
property from the Toolbox. Then add it to the form or to a container control. To
change the properties of a control at design time, on the form, click the control to
select it. Then use the Properties window.The user is permitted to change the properties
according to his desire.
5. Every time you place a control on a form, you switch to this window to adjust the
appearance of the control.

Some of the events and properties of a properties window are listed below in table-01 and
table—02
The following are the most important list of events related a form:(table—01)

76
The following are the most important list of properties related to a form. And these properties can be
set or read while the application is being executed.
table-02

77
Solution Explorer
 The Solution Explorer, which is the right side of the Visual Studio .NET window, provides an
organized view of your projects and their files.
 The Solution Explorer window contains a list of the items in the current solution. It contains
details about your current project. A solution can contain multiple projects, and each project can
contain multiple items.
 Solution Explorer has options to view the code, form design, refresh listed files. Projects files are
displayed in a drop down tree like structure, widely used in Windows based GUI applications.
 In the Solution Explorer, you can open items for editing and add new items to a solution. You
can also search for files within a solution.
The Solution Explorer toolbar has the following buttons:

 The View Code button opens the selected script for editing in the Code Editor.

 The Refresh button updates the Solution Explorer display with information from the database.

 The Show All Files button Show displays all the project items for the selected project, including
those that have been excluded and those that are normally hidden.

 The Properties button Properties button displays the properties for the selected item in the
appropriate window.
Right-clicking on a project or test asset listed in the Solution Explorer displays various menu options,
some of them are listed below:
 Rename
 Import
 Export
 Remove
 Delete
 Debug
 Project and so on.

Setting properties and form control ( Writing and Event procedure)

 A property is a piece of information that characterizes a


control. It could be related to
its location or size. It could be its color, its identification, or any
visual aspect that
gives it presence on the screen. The properties of an object
can be changed either at
design time or at run time. This means that you can set some
properties at design time
and some others at run time.
 The items in the Properties window display in a list set when installing Microsoft
Visual Studio. In the beginning, you may be lost regular when looking for a particular
control because the list is not arranged in a strict order of rules.
 You can rearrange the list. For example, you can cause the items to display in alphabetic order.
To do this, in the title bar of the Properties window, click the Alphabetic button. To restore the
list, you can click the categorized button.
Text Fields: There are fields that expect you to type a value. Most of these fields have
a default value. To change the value of the property, click the name of the property,

78
type the desired value, and press Enter.
Expandable Fields: Some fields have a + button. This indicates that the property has
a set of sub-properties that actually belong to the same property and are set together.
To collapse the field, click the – button. Some of the properties are numeric based,
such as the above Size. With such a property, you can click its name and type two
numeric values separated by a comma.
Boolean Fields: Some fields can have only a true or false value. To change their
setting, you can either select from the combo box or double-click the property to
toggle to the other value.
Action Fields: Some fields would require a value or item that needs to be set through
an intermediary action. Such fields display an ellipsis button. When you click the
button, a dialog box would come up and you can set the value for the field.
There are various types of selection fields. Some of them display just two items. To
change their value, you can just double-click the field. Some other fields have more
than two values in the field. To change them, you can click their arrow and select
from the list. You can also double-click a few times until the desired value is selected.

Also refer properties table-02 in page no-76

Example for creating and executing windows forms


Demonstrate a window form application to add two number:
Steps:
Design a form by dragging appropriate tools from toolbox ,Labels , Textbox and a button
In properties window change the text and of the controls
Name of the two textbox should be changed according to the backend code
TextBox1txtnum1
TextBox2txtnum2

Code:
Public Class Form1

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click


txttotal.Text = Val(txtnum1.Text) + Val(txtnum2.Text)
End Sub
End Class

Output:
Debug and enter two number click add button to get the result.

79
Execution of VB.NET applications can be done in following ways:
 Press the F5 key.
 On the VB menu bar, Run > Start.
 On the VB toolbar, click the VB Run icon (the green arrow)

Data Types in VB.NET


When declaring a variable an indication can be given about what type of data will be
stored. There are many data types permissible under Visual Basic. The following are
common for declaring the usual types of data involved in computer processing.
 Short. A non-decimal (whole) number with a value in the range of -32,768 to
+32,767. 2 byte
 Integer. A non-decimal (whole) number  4 byte
 Long. A non-decimal (whole) number 8 byte
 Single. A floating-point (decimal) positive or negative number with a value in the
range of up to 3.402823E38 (scientific notation). 4 byte
 Double. A floating-point (decimal) positive or negative number8 byte
 Decimal. A decimal number16 byte
 String. Any number of alphabetic, numerical, and special characters. Varies
 Date. Dates in the range between January 1, 0001 to December 31, 9999 and
times in the range between 0:00:00 to 23:59:59. 8 byte
 Boolean. The value True or False. 2 byte
Variables, then, are declared by assigning a name and a data type. The following are
examples of valid variable declarations that can be used to store data of the identified
types.

Dim My_Counter As Integer


Dim My_Salary As Decimal
Dim My_Great-Big-Number As Double
Dim My_Name As String
Dim My_Birthday As Date
Dim My_Current_Time As Date
Dim My_Decision As Boolean

80
Keywords

A keyword is a reserved word with special meanings in the compiler, whose meaning cannot be
changed. Therefore, these keywords cannot be used as an identifier in VB.NET programming such as
class name, variable, function, module, etc.
Some of the keywords of VB.NET:
And , As , ByRef , By Val, Byte, Case, Catch, Char, Date, Dim, Decimal, Declare, Default, Do, Double, End,
EndIf , Else, For ,Next, Finally, Handles, Me, ReDim, Short, Long, Sub, While,Module , MyBase ,Namespace

Visual Basic Statements


A statement is a complete instruction in Visual Basic programs. It may contain keywords, operators,
variables, literal values, constants and expressions.

Statements could be categorized as −


 Declaration statements − these are the statements where you name a variable, constant, or
procedure, and can also specify a data type.

 Executable statements − these are the statements, which initiate actions. These statements can
call a method or function, loop or branch through blocks of code or assign values or expression
to a variable or constant. In the last case, it is called an Assignment statement.

Conditional Statements
If Then statement
If the condition evaluates to true, then the block of code inside the If statement will be executed. If
condition evaluates to false, then the first set of code after the end of the If statement (after the closing
End If) will be executed.

Syntax:
If condition Then
Statements
End If

Example program:
Module decisions
Sub Main()
Dim a As Integer = 10 ‘declaration

' check the boolean condition using if statement


If (a < 20) Then
Console.WriteLine("a is less than 20")
End If
Console.ReadLine()
End Sub
End Module

If Then Else statement


An If statement can be followed by an optional Else statement, which executes when 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.

Syntax:
If(boolean_expression)Then
'statements will execute if the Boolean expression is true
Else
'statements will execute if the Boolean expression is false

81
End If

Example Program:
Module decisions
Sub Main()
'local variable definition '
Dim a As Integer = 100

' check the boolean condition using if statement


If (a < 20) Then

Console.WriteLine("a is less than 20")


Else
Console.WriteLine("a is not less than 20")
End If
Console.ReadLine()
End Sub
End Module

Select Case statement(Switch statement)


 A Select Case 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 select case.
 The Select Case statement provides you with an easy way of testing for the contents of a
variable.
Syntax:
Select test value
Case match value1
…statements
Case match value1
…statements
Case match value1
…statements

……..
[ Case Else
…statements]
End Select

Example Program:
Module decisions
Sub Main()
'local variable definition
Dim grade As Char
grade = "B"
Select grade
Case "A"
Console.WriteLine("Excellent!")
Case "B", "C"
Console.WriteLine("Well done")
Case "D"
Console.WriteLine("You passed")
Case "F"
Console.WriteLine("Better try again")
Case Else
Console.WriteLine("Invalid grade")

82
End Select
Console.WriteLine("Your grade is {0}", grade)
Console.ReadLine()
End Sub
End Module

Looping statements
For Next
A For Next loop is used to repeatedly execute a sequence
of code or a block of code until a given condition is satisfied.
A For loop is useful in such a case when we know how many
times a block of code has to be executed. In VB.NET, the For loop
is also known as For Next Loop.
Syntax:
For counter=start value To end value
[ Statements to be executed ]
Next

Example Program:
Module loops
Sub Main()
Dim a As Byte
' for loop execution
For a = 10 To 20 step 2
Console.WriteLine("value of a: {0}", a)
Next
Console.ReadLine()
End Sub
End Module

Output:
value of a: 10
value of a: 12
value of a: 14
value of a: 16
value of a: 18
value of a: 20

For Each Next statement:


It repeats a group of statements for each element in a
collection. This loop is used for accessing and
manipulating all elements in an array or a VB.Net
collection. And when iteration through each element in the array
or collection is complete, the control transferred to the next
statement to end the loop.

Syntax:
For Each element [ As datatype ] In group
[ statements ]
Next [ element ]

Example Program:
Module loops
Sub Main()

83
Dim anArray() As Integer = {1, 3, 5, 7, 9}
Dim arrayItem As Integer
For Each arrayItem In anArray
Console.WriteLine(arrayItem)
Next
Console.ReadLine()
End Sub
End Module

While statement
The While End loop is used to execute blocks of code or
statements in a program, as long as the given condition is
true. If the condition is true, the body of the while loop
is executed. This process of repeated execution of the body
continues until the condition is not false. And if the
condition is false, control is transferred out of the loop.

Syntax:
While condition
[ statements ]
End Whil
Example Program:
Module loops
Sub Main()
Dim a As Integer = 10
' while loop execution '

While a < 20
Console.WriteLine("value of a: {0}", a)
a=a+1
End While
Console.ReadLine()
End Sub
End Module

Do While statement
It repeats the enclosed block of statements while a Boolean
condition is True or until the condition becomes True. It could be
terminated at any time with the Exit Do statement.
It means that it executes the Do statements, and then it checks the
condition.

Syntax:
Do { While | Until } condition
[ statements ]
Loop
-or-

Do
[ statements ]
Loop { While | Until } condition

Example Program:

84
Module loops
Sub Main()
' local variable definition
Dim a As Integer = 10
'do loop execution
Do
a=a+1
Loop While (a < 20)
Console.ReadLine()
End Sub
End Module

ARRAYS IN VB.NET
An array stores a fixed-size sequential collection of elements of the same type. An array is used to store
a collection of data, but it is often more useful to think of an array as a collection of variables of the same
type.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element
and the highest address to the last element.

Creating Arrays in VB.Net:


To declare an array in VB.Net, you use the Dim statement. For example,

Dim intData(30) ' an array of 31 elements


Dim strData(20) As String ' an array of 21 strings

You can also initialize the array elements while declaring the array. For example,
Dim intData() As Integer = {12, 16, 20, 24, 28, 32}
Dim names() As String = {"Karthik", "Sandhya", _"Shivangi", "Ashwitha", "Somnath"}

Types of Array in VB.NET:


 Fixed-size array
o Multidimensional arrays
o Jagged arrays
 Dynamic-size array

Fixed-size array: The size of array always remains the same-size doesn't change during the program
execution. It means that we have defined the number of elements in the array declaration that will
remain the same during the definition of the elements, and its size cannot be changed.
Syntax:
Dim numbers(5) As Integer

Multi-Dimensional Arrays
VB.Net allows multidimensional arrays. Multidimensional arrays are also called rectangular arrays . A
multi-dimensional array is an array with more than one subscript or dimension.

Syntax:
Dim Arr(10, 20) As Integer //2d array
Dim Arr(10,10,10)As Integer //3d array

Example Program:
Module arrays

85
Sub Main()

Dim a(,) As Integer = {{0, 0}, {1, 2}, {2, 4}, {3, 6}, {4, 8}}
Dim i, j As Integer
For i = 0 To 4
For j = 0 To 1
Console.WriteLine("a[{0},{1}] = {2}", i, j, a(i, j))
Next j
Next i
Console.ReadKey()
End Sub
End Module

Ouput:
a[0,0]: 0
a[0,1]: 0
a[1,0]: 1
a[1,1]: 2
a[2,0]: 2
a[2,1]: 4
a[3,0]: 3
a[3,1]: 6
a[4,0]: 4
a[4,1]: 8

Jagged Arrays
Sometimes the a jagged array called as “array of arrays” and it can store arrays instead of a particular
data type value. A jagged array is a one-dimensional array whose elements contain arrays.

Syntax:
Dim scores As Integer()() = New Integer(5)(){

Example Program:
Module arrays
Sub Main()
'a jagged array of 5 array of integers
Dim a As Integer()() = New Integer(4)() {}
a(0) = New Integer() {0, 0}
a(1) = New Integer() {1, 2}
a(2) = New Integer() {2, 4}
a(3) = New Integer() {3, 6}
a(4) = New Integer() {4, 8}
Dim i, j As Integer

For i = 0 To 4
For j = 0 To 1
Console.WriteLine("a[{0},{1}] = {2}", i, j, a(i)(j))
Next j
Next i
Console.ReadKey()
End Sub
End Module

Dynamic Arrays

86
The size of the array can be changed at the run time- size changes during the program execution.
Dynamic arrays are arrays that can be dimensioned and re-dimensioned as per the need of the program.
You can declare a dynamic array using the ReDim statement.

The Preserve keyword helps to preserve the data in an existing array, when you resize it.

Syntax:
ReDim [Preserve] arrayname(subscripts)

Example Program:
Module arrays
Sub Main()
Dim marks() As Integer
ReDim marks(2)
marks(0) = 85
marks(1) = 75
marks(2) = 90

ReDim Preserve marks(10)


marks(3) = 80
marks(4) = 76
marks(5) = 92
marks(6) = 99
marks(7) = 79
marks(8) = 75

For i = 0 To 10
Console.WriteLine( marks(i))
Next i
Console.ReadKey()
End Sub
End Module
Output:
0 85
1 75
2 90
3 80
4 76
5 92
6 99
7 79
8 75
9 0
10 0

UNIT 3
Application development on .NET
Building Windows Application

Steps:

First, open the Visual Studio then Go to File -> New -> Project to create a new project and then select the
language as Visual C# or Visual Basic from the left menu. Click on Windows Forms App(.NET Framework)
in the middle of current window. After that give the project name and Click OK

87
After that following window will display which will be divided into three parts as follows:

Editor Window or Main Window: Here, you will work with forms and code editing. You can notice the
layout of form which is now blank. You will double click the form then it will open the code for that.

Solution Explorer Window: It is used to navigate between all items in solution. For example, if you will
select a file form this window then particular information will be display in the property window.

Properties Window: This window is used to change the different properties of the selected item in the
Solution Explorer. Also, you can change the properties of components or controls that you will add to the
forms.

Now to add the controls to your WinForms application go to Toolbox tab present in the extreme left side of
Visual Studio. Here, you can see a list of controls. To access the most commonly used controls go to Common
Controls present in Toolbox tab.

To run the program you can use an F5 key or Play button present in the toolbar of Visual Studio. To stop the
program you can use pause button present in the ToolBar. You can also run the program by going to Debug-
>Start Debugging menu in the menubar.

Working with Controls:[Program/Code is compulsory for all the controls]

Timer
The timer control is a looping control used to repeat any task in a given time interval. Once the timer is
enabled, it generates a tick event handler to perform any defined task in its time interval property. It starts
when the start() method of timer control is called, and it repeats the defined task continuously until the timer
stops.

Real time example: StopWatch, Traffic lights

Properties of Timer objects

Property Meaning
Enabled Gets/sets whether the timer is running.
Interval Gets/sets the time in milliseconds between timer ticks.

Methods of Timer objects

88
Method Meaning
Start Starts the timer.
Stop Stops the timer.

Events of Timer objects


Method Meaning
Tick Occurs when the timer interval has elapsed and the timer is enabled.

Steps

 Drag and drop timer control from toolbox.


 Drag and drop Textbox and button and write the code as given below.

Code/Program:

Public class Timer


Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
TextBox1.Text = 1
Timer1.Enabled = True
Button1.Text = "Start"
Button1.BackColor = Color.Green
Button2.Text = "Stop"
Button2.BackColor = Color.Red
Timer1.Interval = 600 'set the time interval
End Sub
Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs)
TextBox1.Text = TextBox1.Text + 1 'Incremenet the TextBox1 by 1
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs)
Timer1.Stop()
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs)
Timer1.Start()
End Sub
End Class

If we click on stop timer will stop and if


click on start again it will start
Output:

PictureBox
PictureBox control is used to display the images on Windows Form. The PictureBox control has an image
property that allows the user to set the image at runtime or design time.
Typically the PictureBox is used to display graphics from a bitmap, metafile, icon, JPEG, GIF, or PNG file.
Example: While applying for any exams through online you upload image into google form.

Properties of Picturebox

89
 Image - The image property is used to display the image on the PictureBox of a Windows form.
 BorderStyle- It is used to set the border style for the picture box in the windows form.
 ImageLocation-It is used to set or get the path or URL of the image displayed on the picture box of
the window form.
 Text - It is used to set text for the picture box controls in the window form.

Methods of Picturebox

 GetStyle() - The GetStyle() method is used to get values for the specified bit style in the PictureBox
control.
 Load() - The Load() method is used to load the specified image from the control using the
ImageLocation property.

Events of Picturebox

 BackColorChanged - It occurs when the property of the backcolor is changed in the PictureBox
control.
 Resize - The resize event occurs when the picture box control is changed.

Steps

Step 1: We have to find the PictureBox control from the toolbox and then drag and drop the PictureBox
control onto the window form, as shown below.
Step 2: Once the PictureBox is added to the form, we can set various properties of the image by clicking on
the PictureBox control. And double click on the button write the below given code.
In the code we need to specify the path of the image that is to be displayed

Program/Code For PictureBox:


Public Class Picbox
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
'Dim Str As String = "C:\desktop\nature.jpg"
PictureBox1.Image = Image.FromFile("C:\desktop\nature.jpg")
PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
PictureBox1.Height = 100
PictureBox1.Width = 200
Label1.Visible = False
End Sub
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs)
Button1.Text = "Show"
End Sub
End Class

Output:

When you click on show


90 button image will be
ComboBox

1. The ComboBox control is used to display a drop-down list of various items. It is a combination of a
text box in which the user enters an item and a drop-down list from which the user selects an item. An
editable text field, giving the user multiple ways to input or select the desired information.
2. The ListBox control enables you to display a list of items to the user that the user can select by
clicking.

Example:Online shopping carts, Course selection

Properties of Combobox
 MaxDropDownItems - The MaxDropDownItems property is used in the combo box control to
display the maximum number of items by setting a value.
 MaxLength - It is used by the user to enter maximum characters in the editable area of the combo
box.
 SelectedItem - It is used to set or get the selected item in the ComboBox Control.
 Sorted - The Sorted property is used to sort all the items in the ComboBox by setting the value.

Events of ComboBox
 FontChanged - It occurs when the property of the font value is changed.
 Format - When the data is bound with a combo box control, a format event is called.
 SelectIndexChanged - It occurs when the property value of SelectIndexChanged is changed.

Steps:
Step 1: We need to drag the combo box control from the toolbox and drop it to the Windows form, as shown
below.
Step 2: Once the ComboBox is added to the form, we can set various properties of the ComboBox by clicking
on the ComboBox control.Also drag and drop listbox and buttons .Write the code as given below

Code/Program For Combobox:


Public Class Combobox
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
If ComboBox1.SelectedIndex > -1 Then
Dim sindex As Integer
sindex = ComboBox1.SelectedIndex
Dim sitem As Object
sitem = ComboBox1.SelectedItem
ListBox1.Items.Add(sitem)

91
End If
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
ComboBox1.Items.Clear()
ComboBox1.Items.Add("TROUSERS")
ComboBox1.Items.Add("TSHIRTS")
ComboBox1.Items.Add("JACKETS")
ComboBox1.Items.Add("JEANS")
ComboBox1.Text = "CLOTHING"
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs)
Handles ComboBox1.SelectedIndexChanged
Label1.Text = ComboBox1.SelectedItem.ToString()
End Sub

Private Sub Button4_Click(sender As System.Object, e As System.EventArgs)


ComboBox1.Items.Clear()
End Sub
End Class
combobox
Output:

Listbox

Selected items will be listed

GroupBox
In Windows form, GroupBox is a container which contains multiple controls on it and the controls are related
to each other. Or in other words, GroupBox is a frame display around a group of controls with a suitable
optional title. Or a GroupBox is used to categorize the related controls in a group.
The main use of a group box is to hold a logical group of RadioButton controls.

Properties of Groupbox:

 AutoSize -This property is used to get or set a value that indicates whether the control resizes based
on its contents.
 AutoSizeMode - This property indicates how the GroupBox behaves when its AutoSize property is
enabled.
 BackColor - This property is used to get or set the background color for the control.
 BorderStyle -This property indicates the border style for the control.
 Size - This property is used to get or set the height and width of the control.
 Visible - This property is used to get or set a value indicating whether the control and all its child
controls are displayed.
 Width - This property is used to get or set the width of the control.

Steps

92
 To create a GroupBox control at design-time, you simply drag and drop a GroupBox control from
Toolbox to a Form in Visual Studio. After you drag and drop a GroupBox on a Form. Once a
GroupBox is on the Form, you can move it around and resize it using mouse and set its properties and
events.
 Also drag and drop radiobuttons and button user needs to select the option from given courselist and
submit.

Code/Program for groupbox:


Public Class Grpbox
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
If RadioButton1.Checked Then
MessageBox.Show("SELECTED BCA COURSE")
ElseIf RadioButton2.Checked Then
MessageBox.Show("SELECTED BSC COURSE")
ElseIf RadioButton3.Checked Then
MessageBox.Show("SELECTED BCOM COURSE")
ElseIf RadioButton4.Checked Then
MessageBox.Show("SELECTED BBM COURSE")
End If
End Sub
End Class

Output:

Groupbox

Scrollbars
 Vertical scrollbar
 Horizontal scrollbar
A ScrollBar control is used to create and display vertical and horizontal scroll bars on the Windows form. It is
used when we have large information in a form, and we are unable to see all the data. Therefore, we used
VB.NET ScrollBar control. Generally, ScrollBar is of two types: HScrollBar for displaying scroll bars and
VScrollBar for displaying Vertical Scroll bars.

Properties of Scrollbars
 BackColor - The BackColor property is used to set the back color of the scroll bar.
 Maximum - It is used to set or get the maximum value of the Scroll Bar control. By default, it is 100.
 Minimum - It is used to get or set the minimum value of the Scroll bar control. By default, it is 0.
 Value- It is used to obtain or set a value in a scroll bar control that indicates a scroll box's current
position.

Events of scrollbars
 Scroll - Occurs when the scroll box is moved either using mouse or keyboard.

93
 ValueChanged - Occurs when the value property has changed by Scroll event or in code

Steps
Step 1: The first step is to drag the HScrollBar and VScrollBar control from the toolbox and drop it on to the
form.
Step 2: Once the ScrollBar is added to the form, we can set various properties of the ScrollBar by clicking on
the HScrollBar and VScrollBar control. Write the code as given below

Code/Program for Scrollbars:


Public Class scrollbar
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Loa
Me.AutoScroll = True
Me.VScrollBar1.Minimum = 0
Me.VScrollBar1.Maximum = 100
Me.VScrollBar1.Value = 0

Me.HScrollBar1.Minimum = 0
Me.HScrollBar1.Maximum = 100
Me.HScrollBar1.Value = 35
End Sub
End Class

NumericUpDown
The Windows Forms NumericUpDown control looks like a combination of a text box and a pair of arrows that
the user can click to adjust a value. The control displays and sets a single numeric value from a list of choices.
Example: If we want to enter our age in google form numericupdown is used.

NumericUpDown Control Properties

1. DecimalPlaces: Gets or sets the number of decimal places to display in NumericUpDown Control.

2. UpDownAlign: Set positions the arrow buttons on the left or the right side of the NumericUpDown.
Default value is Right.

3. Increment: Gets or sets the value to increment or decrement the NumericUpDown.

Steps
 To create a NumericUpDown control at design-time, you simply drag and drop a NumericUpDown
control from Toolbox to a Form in Visual Studio.
 Once a NumericUpDown is on the Form, you can move it around and resize it using mouse and set its
properties and events.Drag a button and double click on the button write the below code.
 The ToString method is used to return a string representation of an object.
 String format() method returns a formatted string using the given locale, specified format string, and
arguments

Code/Program :

Public Class Numericupdown


Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Button1.Text = "Save"
MessageBox.Show(String.Format("The age is {0}", NumericUpDown1.Value.ToString))
End Sub
End Class

94
Output:

ProgressBar
The ProgressBar control is typically used when an application performs tasks such as copying files or printing
documents.
The Window ProgressBar control is used by the user to acknowledge the progress status of some defined
tasks, such as downloading a large file from the web, copying files, installing software, calculating complex
results, and more.
The main properties of a progress bar are Value, Maximum and Minimum. The Minimum and Maximum
properties are used to set the minimum and maximum values that the progress bar can display. The Value
property specifies the current position of the progress bar.

Properties of Progressbar

 Maximum - It is used to set the maximum length of the progress bar control in the windows form.
 Minimum - It is used to set or get the minimum value of the progress bar control in the windows
form.
 Padding - The padding property is used to create a space between the edges of the progress bar by
setting the value in the progressbar control.

Events of ProgressBar
 Leave - The Leave event occurs when the focus leaves the progress bar control.
 MouseClick - A MouseClick event occurred when the user clicked on the progress bar control by the
mouse.

Methods of ProgressBar:
 ForeColor - The ForeColor method is used to reset the forecolor to its default value.
 ToString - The ToString method is used to display the progress bar control by returning the string.
 Increment - It is used to increase the current state of the progress bar control by defining the specified
time.
Steps
Step 1: The first step is to drag the ProgressBar control from the toolbox and drop it on to the Form.

Step 2: Once the ProgressBar is added to the Form, we can set various properties of the ProgressBar by
clicking on the ProgressBar control. Drag a button so that when user click on button starts downloading

Code/Program:
Public Class Progressbar

95
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
ProgressBar1.Visible = True

Dim i As Integer
ProgressBar1.Minimum = 0
ProgressBar1.Maximum = 100

For i = 0 To 100 Step 1


ProgressBar1.Value = i
If i > ProgressBar1.Maximum Then
i = ProgressBar1.Maximum

End If
Next
MsgBox("Successfully Completed")
End Sub
End Class

Output:

TrackBar
The Windows Forms TrackBar control (also sometimes called a "slider" control) is used for navigating
through a large amount of information or for visually adjusting a numeric setting. The TrackBar control has
two parts: the thumb, also known as a slider..
Example: Phone Brightness, Youtube videos.

Properties
 The key properties of the TrackBar control are Value, TickFrequency, Minimum, and Maximum.
TickFrequency is the spacing of the ticks. Minimum and Maximum are the smallest and largest values
that can be represented on the track bar. Two other important properties are SmallChange and
LargeChange.
 The value of the LargeChange property is the number of positions the thumb moves in response to
having the PAGE UP or PAGE DOWN key pressed, or in response to mouse clicks on the track bar
on either side of the thumb.

Steps
Step1:To create a TrackBar control at design-time, you simply drag and drop a TrackBar control from
Toolbox to a Form in Visual Studio. After you drag and drop a TrackBar on a Form,
Step2: You can configure ranges through which the value of the Value property of a track bar scrolls by
setting the Minimum property to specify the lower end of the range and the Maximum property to specify the
upper end of the range.

96
Code/Program:

Public Class Trackbar


Private Sub TrackBar1_Scroll(sender As System.Object, e As System.EventArgs)
Label1.Text = "" + TrackBar1.Value.ToString()

End Sub
End Class

Output:

Drag this to increase and


decrease

Subroutines and Functions in VB.NET


Dividing the code into procedures makes the project a modular one. Procedures are made up of series of
Visual Basic statements that, when called, are executed. After the call is finished, control returns to the
statement that called the procedure.

PROCEDURE

SUBROUTINE FUNCTION
DOES NOT RETURN VALUE RETURNS A VALUE TO CALLING
TO CALLING FUNCTION FUNCTION

Subroutine
A Sub procedure also called as subroutine is a separate set of codes that are used in VB.NET programming to
execute a specific task, when it is called and it does not return any values. The Sub procedure is enclosed by
the Sub and End Sub statement. The Sub procedure is similar to the function procedure for executing a
specific task except that it does not return any value, while the function procedure returns a value.

Syntax for Subroutine


[Modifiers] Sub SubName [(ParameterList)]
[Statements]
End Sub
Example Program:
Pass by value
Module paramByval
Sub swap(ByVal x As Integer, ByVal y As Integer)
Dim temp As Integer
temp = x
x=y
y = temp
End Sub

97
Sub Main()
Dim a As Integer = 100
Dim b As Integer = 200 ' local variable definition
swap(a, b) ' calling a function to swap the values '
Console.WriteLine("After swap, value of a : {0}", a)
Console.WriteLine("After swap, value of b : {0}", b)
Console.ReadLine()
End Sub
End Module

Pass by Reference
Refer same above program instead ByVal put ByRef
Module paramByval
Sub swap(ByVal x As Integer, ByVal y As Integer)
Dim temp As Integer
temp = x
x=y
y = temp
End Sub
Sub Main()
Dim a As Integer = 100
Dim b As Integer = 200 ' local variable definition
swap(a, b) ' calling a function to swap the values '
Console.WriteLine("After swap, value of a : {0}", a)
Console.WriteLine("After swap, value of b : {0}", b)
Console.ReadLine()
End Sub
End Module

Functions
A function procedure is a group of VB.NET statements. It begins with a Function keyword and ends with an
End Function keyword. It is generally used to perform a task and return a value back to the calling code. It has
return keyword .
Subroutines usually perform actions and they don't return any result. Functions, on the other hand, perform
some calculations and return a value.
There are two types of Functions:
1. User-Defined
2. Built-in functions
Syntax for Functions:
[Modifiers] Function FunctionName [(ParameterList)] As ReturnType
[Statements]
End Function
Program:
Passing by Value
Module Find_Sum
' Create the Sum() Function and pass the parameters.
Function Sum(ByVal n1 As Integer, ByVal n2 As Integer) As Integer
Dim sum As Integer = 0 ‘local variable
sum = n1 + n2
Return sum
End Function
Dim a As Integer = 50
Dim b As Integer = 20
Dim total As Integer
total = Sum(a, b) ‘calling function

98
Console.WriteLine(" Sum of two number is : {0}", total)
Console.ReadKey()
End Sub
End Module

Passing By Reference
Refer same above program instead ByVal put ByRef
Module Find_Sum
' Create the Sum() Function and pass the parameters.
Function Sum(ByRef n1 As Integer, ByRef n2 As Integer) As Integer
Dim sum As Integer = 0 ‘local variable
sum = n1 + n2
Return sum
End Function
Dim a As Integer = 50
Dim b As Integer = 20
Dim total As Integer
total = Sum(a, b) ‘calling function
Console.WriteLine(" Sum of two number is : {0}", total)
Console.ReadKey()
End Sub
End Module

Built-in Functions in VB.NET

Visual Basic has many built-in functions for manipulating text and carrying out mathematical operations, as
well as the ability to format data in both standard and user-defined styles.
Some of the built-in functions are explained below:

MsgBox() Function
The MsgBox() function displays a message in a pop-up message box . The user is expected to respond by
clicking on a button in order to be able to continue.
returnVal = MsgBox (prompt, styleVal, title)
 The prompt parameter is a string value that supplies the message to be displayed.
 The returnVal value returned by the MsgBox() function is an integer value that indicates which button
the user has clicked in response to the message box being displayed.
 The title parameter is another string literal or string variable that supplies the title for the message box.
Example: MsgBox(messageText.Text, vbYesNo Or vbQuestion)

The styles and return values are listed below:

vbOkOnly Ok
vbYesNo Yes,No
vbOkCancel Ok,Cancel
vbAbort Abort
vbRetry Retry
vbYesNoCancel Yes,No,Cancel
vbIgnore Ignore
vbRetryCancel Retry,Cancel

99
InputBox() Function

The InputBox() function displays a pop-up input box into which the user can type a message. The user is
expected to enter their message, then click on a button ("Cancel" or "OK") in order to continue.

returnString = InputBox (prompt, title, defaultText, xpos, ypos)

 The returnString returned by the InputBox() function is the text entered by the user.
 The defaultText parameter can be used to enter default content in the input box (although it would
probably be left blank in most cases).
 The xpos and ypos parameters specify the x and y coordinates for the input box on screen.

Example: Dim str As String


str = InputBox("Enter the Message", "Input Box", "Enter Here")
If str = "Enter Here" Or str = "" Then
Exit Sub
End If
MsgBox(str, vbOK Or vbQuestion)

String Functions

UCase (str) Converts the string referred to by str to all upper-case characters, and returns the result.
LCase (str) Converts the string referred to by str to all lower-case characters, and returns the result.
Trim (str) Removes the white space (if any) at either end of the text string referred to by str .

LTrim (str) Removes the white space (if any) at the left-hand end of the text string referred to by str

RTrim (str) Removes the white space (if any) at the right-hand end of the text string referred to by str

Maths functions

Math.Sqrt (n) Returns the square root of a number, n.


Math.Abs (n) Returns the absolute value of a number, n.
Int (n) Returns the integer part of a floating point number, n, for
positive numbers, or the next smallest integer value for
negative numbers.
Math.Exp (n) Returns the exponential value of a number, n – i.e. e n.
Math.Log (n) Returns the natural logarithm of a number, n.

Formatting numbers

The Format() function allows you to specify precisely how numeric values are displayed. The function is used
as follows:

Format (n, "styleArg")

General Number Displays n with no separator between thousands.


Fixed Displays n with no separator between thousands,
and rounds it up (or down) to two decimal places.
Standard Displays n with separators between thousands, and
rounds it up (or down) to two decimal places.

100
Percent Displays n as a percentage, rounds it up (or down) to
two decimal places, and adds a "%" symbol.

Formatting the date and time

The Format() function can also be used to specify how date and time values are displayed. The function is
used as follows:

Format (Date, "styleArg")

"General Date" Displays the date and time in the format: dd/mm/yyyy hh:mm:ss
"Long Date" Displays the date in the format: 06 October 2009
"Short Date" Displays the date in the format: dd/mm/yyyy
"Long Time" Displays the time in the format: h:mm:ss

Database Applications
Database systems are designed to manage large bodies of information. Management of data involves both
defining structures for storage of information and providing mechanisms for the manipulation of information.
Databases are useful in many different scenarios for storing data. It is typical to use a database when different
sets of data needs to be linked together, such as:

Pupils in a school and their grades,Customer records and sales information,Patients’ and doctors’
records,Transactions between different bank accounts,Taxpayers and income tax payments

Database Applications:

Social Media Sites − By filling the required details we are able to access social media platforms. Many users
sign up daily on social websites such as Facebook, Pinterest and Instagram. All the information related to the
users are stored and maintained with the help of DBMS.

Finance − Now-a-days there are lots of things to do with finance like storing sales, holding information and
finance statement management etc. these all can be done with database systems.

Military − In military areas the DBMS is playing a vital role. Military keeps records of soldiers and it has so
many files that should be kept secure and safe. DBMS provides a high security to military information.

Online Shopping − Now-a-days we all do Online shopping without wasting the time by going shopping with
the help of DBMS. The products are added and sold only with the help of DBMS like Purchase information,
invoice bills and payment.

Banking − Banking is one of the main applications of databases. We all know there will be a thousand
transactions through banks daily and we are doing this without going to the bank. This is all possible just
because of DBMS that manages all the bank transactions.

Manufacturing − Manufacturing companies make products and sell them on a daily basis. To keep records of
all those details DBMS is used.

Airline Reservation system − Just like the railway reservation system, airlines also need DBMS to keep
records of flights arrival, departure and delay status.

101
Library Management System − Now-a-days it’s become easy in the Library to track each book and maintain
it because of the database. This happens because there are thousands of books in the library. It is very difficult
to keep a record of all books in a copy or register. Now DBMS used to maintain all the information related to
book issue dates, name of the book, author and availability of the book.

Why database is required?

1. Accurate
A database is pretty accurate as it has all sorts of build in constraints, checks etc. This means that the
information available in a database is guaranteed to be correct in most cases.

2. Easy to update data


In a database, it is easy to update data using various Data Manipulation languages (DML) available.
One of these languages is SQL.

3. Security of data
Databases have various methods to ensure security of data. There are user logins required before
accessing a database and various access specifiers. These allow only authorised users to access the
database.

4. Data integrity
This is ensured in databases by using various constraints for data. Data integrity in databases makes
sure that the data is accurate and consistent in a database.

5. Manages large amounts of data


A database stores and manages a large amount of data on a daily basis. This would not be possible
using any other tool such as a spreadsheet as they would simply not work.

ADO.NET Connectivity
INTRODUCTION TO ADO.NET

ADO.NET stands for ActiveX Data Object is a large set of .NET classes that enable us to retrieve
and manipulate data, and update data sources, in very many ways.
ADO.NET is a bridge between the user application(frontend) and server(backend).Data coming from
application must be stored in database and ADO.NET provides various classes to store the data.
It is a module of .Net Framework which is used to establish connection between application and data
sources. Data sources can be such as SQL Server and XML. ADO.NET consists of classes that can be
used to connect, retrieve, insert and delete data.
All the ADO.NET classes are located into System.Data.dll and integrated with XML classes located
into System.Xml.dll.

102
ADO.NET has two main components that are used for accessing and manipulating data are the .NET
Framework data provider and the DataSet.
Dataprovider A .NET Framework data provider is used for connecting to a database, executing
commands, and retrieving results.
Dataset The DataSet, which is an in-memory cache of data retrieved from a data source, is a major
component of the ADO.NET architecture

DataProvider

ADO vs ADO.NET

ADO ADO.NET
o It is a COM(Component Object o It is a CLR(Common Language Runtime)
Modelling) based based Library.
o Library.
o Locking features is available o Locking features is not available
o ADO works in the connected mode to o ADO.Net works in the disconnected
access data mode to access data.
o Data is stored in Binary Format o Data is stores in XML
o XML integration is not possible o XML integration is possible
o It uses RecordSet to store the data from o It uses Dataset to store the data from
datasource datasource
o Using classic ADO, you can obtain o Dataset object of ADO.Net includes
information from one table or set of collection of DataTable wherein each
tables through join. You cannot fetch DataTable will contain records fetched
records from multiple tables from a particular table. Hence multiple
independently table records are maintained
independently

103
o In ADO, You can create only Client side o In ADO.Net, You can create both Client
cursor. & Server side cursor

o Firewall might prevent execution of o ADO.Net has firewall proof and its
Classic ADO execution will never be interrupted
o You cannot send multiple transaction o You can send multiple transaction using
using a single connection instance a single connection instance.
o ADO requires data to be converted to o ADO.NET does not require complex
data types supported by receiving system. conversions that wasted processor time.
o It has a less number of data types o It has a huge and rich collection of data
types.
o ADO is less secured. o ADO.NET much secured as compared to
ADO.
o ADO technology have less scalable. o ADO.NET have more scalability with the
use of locking mechanism.
o ADO have a poor performance. o In ADO.NET performance is much better
as compared to ADO.
o ADO technology use more resources as o ADO.NET conserves limited resources.
compared to ADO.NET.

Architecture of ADO.NET

It is a part of the .NET Framework which is used to establish a connection between the .NET Application and
different data sources. So, ADO.NET is nothing but a component in .NET Framework that helps us to fetch
data from different data sources(server) as well as also used to send data to different data sources(server) such
as SQL Server, Oracle, MySQL, XML, etc

The ADO.NET architecture comprises following important components. They are as follows:

1. Connection

104
2. Command
3. DataReader
4. DataAdapter
5. DataSet

Diagram

Dataprovider: It is a bridge between the user application and database. Data provider is used to connect to the
database, execute commands and retrieve the record. It is lightweight component with better performance.
They are the Microsoft SQL Server Data Provider , OLEDB Data Provider and ODBC Data Provider . SQL
Server uses the SqlConnection object , OLEDB uses the OleDbConnection Object and ODBC uses
OdbcConnection Object respectively.

Connection: The connection object is the first important component of your application. It is required to
connect to a backend database that may be SQL Server, Oracle, MySQL, etc. The connection is created using
the connection object and a backend data source must be connected to using the connection. To use this class,
you have to first create an object of this class. Hence, here we create a variable called 'cnn' which is of the type
SqlConnection.

Example: using (SqlConnection connection = newSqlConnection(connectionString)) {


connection.Open();}

Command: The second important component is the command object. When we discuss databases such as
SQL Server, Oracle, MySQL, then speak SQL, it is the command object that we use to create SQL queries.
After you create your SQL queries, you can execute them over the connection using the command object.
Example: select * FROM customers;
DELETE FROM customers WHERE city=’Mysuru’;

105
DataReader: We can only read the records in the forward mode with DataReader. Here, you should
familiarize yourself with three things: read-only, connected, and forward modes. The DataReader cannot be
created directly from code, they can created only by calling the ExecuteReader method of a Command Object.
The DataReader is a good choice when you're retrieving large amounts of data because the data is not cached
in memory.

reader = command.ExecuteReader();

DataSet: It is a Disconnected record set that can be browsed in both i.e. forward and backward mode. It is not
read-only i.e. you can update the data present in the data set. Actually, DataSet is a collection of DataTables
that holds the data and we can add, update, and delete data in a data table. DataSet gets filled by somebody
called DataAdapter. For example, the test scores of each student in a particular class is a data set.

DataAdapter: A data adapter a object serves as a bridge between a data set object and Data Source such as a
database to retrieve and save the data. Data adapter contains a set of database commands and a database
connection, which we use to fill a dataset object and update the Data Source.

SqlDataAdapter sde = new SqlDataAdapter

The properties are given below.

• Select command retrieves rows from Data Source


• Insert command writes inserted rows from data set into Data Source
• Update command writes modified rows from data set into Data Source.
• Delete command deletes rows from Data Source.

DataReader

This class is used to read data from SQL Server database. We can only read the records in the forward mode
with DataReader. Here, you should familiarize yourself with three things: read-only, connected, and forward
modes. The DataReader cannot be created directly from code, they can created only by calling the
ExecuteReader method of a Command Object.

Properties

106
Connection It is used to get the SqlConnection associated with the
SqlDataReader.

HasRows It is used to get a value that indicates whether the SqlDataReader


contains one or more rows.

IsClosed It is used to retrieve a boolean value that indicates whether the


specified SqlDataReader instance has been closed.

Depth It is used to get a value that indicates the depth of nesting for the
current row.

Methods of DataReader Class:

Close() It is used to closes the SqlDataReader object.

Read() It is used to read record from the SQL Server database.

GetValue(Int32) It is used to get the value of the specified column in its native format.

To create a SqlDataReader instance, we must call the ExecuteReader method of the SqlCommand object.

reader = command.ExecuteReader();

Program:

static void HasRows(SqlConnection connection)

{
using (connection)
{
SqlCommand command = new SqlCommand( "SELECT CategoryID, CategoryName FROM
Categories;",connection);
connection.Open(); //connection open
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("{0}\t{1}", reader.GetInt32(0),
reader.GetString(1));
}
}
else
{
Console.WriteLine("No rows found.");
}
reader.Close();
conn.Close(); //connection close
}
Data Adapter

107
A data adapter a object serves as a bridge between a data set object and Data Source such as a database to
retrieve and save the data.Data adapter contains a set of database commands and a database connection, which
we use to fill a dataset object and update the Data Source.

SqlDataAdapter sde = new SqlDataAdapter

We can also specify, which action we want to perform by using one of following four data adapter properties,
which executes a SQL statement.
The properties are given below.
 Select command retrieves rows from Data Source
 Insert command writes inserted rows from data set into Data Source
 Update command writes modified rows from data set into Data Source.
 Delete command deletes rows from Data Source.

Methods of DataAdapter:
 FillUse this method of a SQL data adapter to add or refresh row from a Data Source and place them in
a Data Set table.
 UpdateUse this method of data adapter object to transmit the changes to a dataset table to the
corresponding Data Source.
 CloseUse this method for the connection to a database

An Program for creating Data adapter:

Code/Program:
public partial class DataSetDemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection("data source=.; database=student; integrated
security=SSPI"))
{
SqlDataAdapter sde = new SqlDataAdapter("Select * from student", con);
DataSet ds = new DataSet();
sde.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
}
}

Accessing Data with ADO.NET: [Refer Diagram Architecture ADO.NET PAGE


NO:-106]
•Data Connection objects: We must have a data connection like OleDbConnection, OdbcConnection, Oracle
Conncection or SqlConnection to communicate with a data source.

108
•Data Adapters: It communicate between a data source and dataset. We can use OleDbAdapter,
OdbcAdapter, Oracle Adapter or SqlAdapter.
• Command Objects: Data adapters can read, write, add, update and delete the records in a datasource. Data
adapters support 4 properties SelectCommand, InsertCommand, DeleteCommand, UpdateCommand.
• Dataset: The structure of a dataset is similar to relational database. It gives you access to an object model of
tables, rows and columns.
• Data Table: It holds a data table from a data source. It contain two properties: Columns and rows which is
collection of Datacolumn and Datarow objects.
•Data Reader: It hold a read only, forward only.
• Data Views: It represent a customized view of a single table that can be filtered, searched or sorted.
• Constraint Objects: Dataset supports constraint to check data integrity. Ex: Unique constraint and foreign
constraint
• Data Relation Objects: It specify a relationship between parent and child tables based on a key that share.
• Data Row/Column: A particular row/column in a data table

Using Basic SQL


 Using the SELECT Statementselect * FROM customers
 Using Where ClausesSelect * from customers WHERE city=’mysuru’;
We can use <,>, <=,>=,BETWEEN, LIKE, IN, AND, OR,NOT

 Using the DISTINCT statement select DISTINCT name from customers;

 Using ORDERBY, GROUPBY, HAVING


o select * from customers ORDERBY custID;
o select from customers GROUPBY city;
o select from customers HAVING CITY like ‘Madurai’;

 Built-in-Functions COUNT,SUM, MIN, MAX, AVG

 Using the DELETE Statement


DELETE FROM customers WHERE city=’Mysuru’;
 Using the UPDATE Statement
UPDATE customers SET city=’Boston’ where city=’York’

 Joining Tables
We can to inner join, outer join using multiple tables.

NOTE:[DRAW ARCHITECTURE DIAGRAM FOR ACCESSING OF ADO.NET]


Steps to create database connections:
 Click the Connections tab .
 Click New connection and choose Database from the menu. The New connection window appears.
 Choose the database type you want to connect to. ...
 Provide the connection properties for your database. ...
 Click add

ASP.NET
Programming web applications with web forms/ASP.NET applications with ADO.NET:

109
ASP.NET is a free web framework for building great websites and web applications using HTML, CSS,
and JavaScript.
ASP.NET is a web development platform, which provides a programming model, a comprehensive
software infrastructure and various services required to build up robust web applications for PC, as
well as mobile devices.
ASP.NET is a part of Microsoft .Net platform. ASP.NET applications are compiled codes, written using
the extensible and reusable components or objects present in .Net framework. These codes can use the
entire hierarchy of classes in .Net framework.
The ASP.NET application codes can be written in any of the following languages:

 C#
 Visual Basic.Net
 Jscript

Web Forms:
Web Forms are pages that your users request using their browser. These pages can be written using a
combination of HTML, client-script, server controls, and server code. When users request a page, it is
compiled and executed on the server by the framework, and then the framework generates the HTML
markup that the browser can render. An ASP.NET Web Forms page presents information to the user in
any browser or client device.

Using Visual Studio, you can create ASP.NET Web Forms. The Visual Studio Integrated Development
Environment (IDE) lets you drag and drop server controls to lay out your Web Forms page. You can
then easily set properties, methods, and events for controls on the page or for the page itself. To write
server code to handle the logic for the page, you can use a .NET language like Visual Basic or C#.

What is Web Application?


A web application is an application installed only on the web server which is accessed by the users
using a web browser like Microsoft Internet Explorer, Google Chrome, Mozilla FireFox, Apple Safari, etc.
There are also some other technology like Java, PHP, Perl, Ruby on Rails, etc. which can be used to
develop web applications. Web applications provide the cross-platform feature. The user needs only a
web browser to access a web application.

ASP.NET has multiple features and provides many tools to create and develop web applications. Here
are some of the features of web forms:

1. Server Controls
It provides a vast set of server controls. These controls are like objects, and they run when they are
requested and rendered to the browser. Some web pages are similar to HTML elements like text-box,
button, checkbox, and hyperlink.

2. Mater Pages
Mater Pages is responsible for the consistent layout of our web applications. It gives a proper
appearance and standard to different pages.

3. Routing

110
URL routing can be configured to a web application. A request URL is a URL that a user enters in a
browser to browse in a specific place.

4. Security
Security always plays a crucial role in software development. ASP.NET provides different configuration
options and extensibility points to make our systems more secure.

Simple Example of Web Forms[should be written if any question asked upon ASP.NET]
 Creating New Web Forms
 To add a new form, select the project, right-click, and add a new item.
 Click the web forms option in the left corner, and select web form.
 Now click on the add button.
 Double click on this form, and this will show some auto-generated code

Program:[should be written if any question asked upon ASP.NET]


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Welcome to the Web Forms!</h2>
</div>
</form>
</body>
</html>

Creating a web application of dynamic login page.

Steps to create ASP.net login page:


 Step 1. Creating an empty ASP.NET website.
 Step 2. Designing the Login web page:- Once you add a web form, you can design a simple
login page as you can see in the screenshot below. In case, you want to make it more stylish,
then feel free to use CSS or any front end framework
 Step 3. Creating SQL database:- After designing the login page, let’s now create an SQL
database and add it to our project. To add SQL database in your ASP.net website, use the Control
+ Shift + A shortcut and then select SQL database from the dialog box.Visual Studio will show a
prompt to create a folder app_data. Simply, click on the OK button to add the SQL database. add
a table UserDetails from where we will match the credentials of the users. To add the table,
right-click on the Tables menu in the Server Explorer and select the Add New Table option. After
that, Visual Studio will open a tab where you can write an SQL query to create the table.
 Step 4. Configuring web.config file:-Before configuring the web.config file, you need to copy
the connection string of your SQL database.
 Step 5. Coding ASP.Net login form:-Double click on the Login button (on the Design tab) to
open the C Sharp/Vb file of your Login page.

111
Program:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<div>
<h1 style="text-align: center">Create Account</h1>
</div>
<table>
<tr>
<td>Enter Username:
</td>
<td>
<asp:TextBox ID="txtUserNameAC" runat="server" />
<asp:RequiredFieldValidator ID="rfvUser" ErrorMessage="Please
enter Username" ControlToValidate="txtUserNameAC" runat="server" />
</td>
</tr>
<tr>
<td>Enter Password:
</td>
<td>
ControlToValidate="txtPWDAC" ErrorMessage="Please enter Password" />
</td>
</tr>
<tr>
<td></td>
<td>
<asp:Button ID="createAccountSubmit" runat="server" Text="Create
Account" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>

SqlConnection con = new


SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from UserDetails where username =@username
and Password=@Password", con);

112
cmd.Parameters.AddWithValue("@username", TextBox1.Text);
cmd.Parameters.AddWithValue("@Password", TextBox2.Text);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
Response.Redirect("LoginPage.aspx");
}
else
{
Label3.Visible = true;
Label3.Text = "Wrong Details";
}

******GOOD LUCK******
-------------------------------------------------------------------------------------------------------------------------------------

113

You might also like