Net All
Net All
Class and Object are the basic concepts of Object-Oriented Programming which revolve around
the real-life entities. 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.
Generally, a class declaration contains only a keyword class, followed by
an identifier(name) of the class. But there are some optional attributes that can be used with
class declaration according to the application requirement. In general, class declarations can
include these components, in order:
• Modifiers: A class can be public or internal etc. By default modifier of the class is internal.
• Keyword class: A class keyword is used to declare the type class.
• Class Identifier: The variable of type class is provided. The identifier(or name of the
class) should begin with an initial letter which should be capitalized by convention.
• Base class or Super class: The name of the class’s parent (superclass), if any, preceded by
the : (colon). This is optional.
• Interfaces: A comma-separated list of interfaces implemented by the class, if any,
preceded by the : (colon). A class can implement more than one interface. This is optional.
• Body: The class body is surrounded by { } (curly braces).
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. The following is an example of a very simple class declaration
Class classname
{
//class-body
}
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.
Member Access Modifiers
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.
Objects
}
}
public class Class1
{
static void Main()
{
Exercise exo = new Exercise();
}
}
C# Constructors
A constructor is a special method of the class which gets automatically invoked whenever an
instance of the class is created. Like methods, a constructor also contains the collection of
instructions that are executed at the time of Object creation. It is used to assign initial values to
the data members of the same class.
• Constructor of a class must have the same name as the class name in which it resides.
• A constructor cannot be abstract, final, and Synchronized.
• Within a class, you can create only one static constructor.
• A constructor doesn’t have any return type, not even void.
• A static constructor cannot be a parameterized constructor.
• A class can have any number of constructors.
• Access modifiers can be used in constructor declaration to control its access i.e which other
class can call the constructor.
Types of Constructor
1. Default Constructor
2. Parameterized Constructor
C# Default Constructor:
A constructor which has no argument is known as default constructor. It is invoked at the time of
creating object.
using System;
public class Employee
{
public Employee()
{
Console.WriteLine("Default Constructor Invoked");
}
public static void Main(string[] args)
{
Employee e1 = new Employee();
Employee e2 = new Employee();
}
}
Output:
Default Constructor Invoked
Default Constructor Invoked
C# Parameterized Constructor
A constructor which has parameters is called parameterized constructor. It is used to provide
different values to distinct objects.
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", 890000f);
Employee e2 = new Employee(102, "Mahesh", 490000f);
e1.display();
e2.display();
}
}
Output:
C# Constructor Overloading:
In C#, similar to method overloading, we can also overload constructors. For constructor
overloading, there must be two or more constructors with the same name but different
• number of parameters
• types of parameters
• order of parameters
Different number of parameters
We can overload the constructor if the number of parameters in a constructor are different.
using System;
namespace ConstructorOverload {
class Car {
Console.WriteLine();
Console.ReadLine();
}
}
}
Output-
car constructor
Car constructor with one parameter
Brand: Bugatti
Different types of parameters:
using System;
namespace ConstructorOverload {
class Car {
Console.WriteLine();
Console.ReadLine();
}
}
}
Output-
Brand: Lamborghini
Price: 50000
namespace ConstructorOverload {
class Car {
Console.WriteLine();
Console.ReadLine();
}
}
}
Output-
Brand: Bugatti
Price: 50000
Speed: 60 km/hr
Color: Red
C# Sealed Class:
Sealed classes are used to restrict the users from inheriting the class. A class can be sealed
by using the sealed keyword. The keyword tells the compiler that the class is sealed, and
therefore, cannot be extended. No class can be derived from a sealed class.
A method can also be sealed, and in that case, the method cannot be overridden. However, a
method can be sealed in the classes in which they have been inherited. If you want to declare a
method as sealed, then it has to be declared as virtual in its base class.
The following class definition defines a sealed class in C#:
// C# code to define
// a Sealed Class
using System;
// Sealed class
sealed class SealedClass {
// Calling Function
public int Add(int a, int b)
{
return a + b;
}
}
class Program {
// Main Method
static void Main(string[] args)
{
class Bird {
// Driver Class
class Program {
// Main Method
static void Main()
{
}
}
The static keyword in C# language is used to declare static classes and static class members. The
static classes and static class members such as constructors, fields, properties, methods, and events
are useful when only one copy of the object (class or class members) are needed and shared among
all instances (objects) of a type (and members).
In C#, static is a keyword or modifier that belongs to the type not instance. So instance is not
required to access the static members. In C#, static can be field, method, constructor, class,
properties, operator and event.
Memory efficient: Now we don't need to create instance for accessing the static members, so it
saves memory. Moreover, it belongs to the type, so it will not get memory each time when instance
is created.
Output:
101 Sonoo
102 Mahesh
103 Ajeet
Total Objects are: 3
C# String
In C#, a string is a sequence of characters.
We use the string keyword to create a string. For example,
// create a string
string str = "C# Programming";
Example: Create string in C#
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
// create string
string str1 = "C# Programming";
string str2 = "Programiz";
// print string
Console.WriteLine(str1);
Console.WriteLine(str2);
Console.ReadLine();
}
}
}
Output:
C# Programming
Programiz
String Operations
C# string provides various methods to perform different operations on strings. We will look into
some of the commonly used string operations.
// create string
string str = "C# Programming";
Console.WriteLine("string: " + str);
Console.ReadLine();
}
}
}
Output
string: C# Programming
Length: 14
// create string
string str1 = "C# ";
Console.WriteLine("string str1: " + str1);
// create string
string str2 = "Programming";
Console.WriteLine("string str2: " + str2);
Console.ReadLine();
}
}
}
Output
string str1: C#
string str2: Programming
Joined string: C# Programming
// create string
string str1 = "C# Programming";
string str2 = "C# Programming";
string str3 = "Programiz";
Console.ReadLine();
}
}
}
Output
string str1 and str2 are equal: True
string str1 and str3 are equal: False
Value Types:
A data type is a value type if it holds a data value within its own memory space. It means the
variables of these data types directly contain values.
• bool
• byte
• char
• decimal
• double
• enum
• float
• int
• long
• sbyte
• short
• struct
int x = 10;
int y = x;
y = 20;
// after this statement x holds value 10 and y holds value 20
Reference Type:
Unlike value types, a reference type doesn't store its value directly. Instead, it stores the address
where the value is being stored. In other words, a reference type contains a pointer to another
memory location that holds the data.
For example, consider the following string variable:
string s = "Hello World!!";
• String
• Arrays (even if their elements are value types)
• Class
• Delegate
ChangeReferenceType(std1);
Console.WriteLine(std1.StudentName);
}
Output:
Rudransh
Boxing
• Boxing is a mechanism in which value type is converted into reference type.
• It is implicit conversion process in which object type (super type) is used.
• In this process type and value both are stored in object type
Unboxing
Example
int i, j;
object obj;
string s;
i = 32;
obj = i; // boxed copy
i = 19;
j = (int) obj; // unboxed
C# Exception Handling:
In C#, exception is an event or object which is thrown at runtime. All exceptions the derived
from System.Exception class. It is a runtime error which can be handled. If we don't handle
the exception, it prints exception message and terminates the program.
C# Exception Classes
All the exception classes in C# are derived from System.Exception
Exception Description
C# try/catch
Output:
C# try/catch example
using System;
public class ExExample
{
public static void Main(string[] args)
{
try
{
int a = 10;
int b = 0;
int x = a / b;
}
catch (Exception e) { Console.WriteLine(e); }
C# Encapsulation:
Encapsulation is defined as the wrapping up of data and information under a single unit. It is the
mechanism that binds together the data and the functions that manipulate them. In a different
way, encapsulation is a protective shield that prevents the data from being accessed by the code
outside this shield.
Technically in encapsulation, the variables or data of a class are hidden from any other class
and can be accessed only through any member function of its own class in which they are
declared.
As in encapsulation, the data in a class is hidden from other classes, so it is also known
as data-hiding.
Encapsulation can be achieved by: Declaring all the variables in the class as private and
using C# Properties in the class to set and get the values of variables.
Abstraction: Encapsulation allows you to create a level of abstraction between the internal
workings of an object and its external behavior. This makes it easier to understand the code and
reduces the risk of errors caused by changing the internal data directly.
Modularity: Encapsulation allows you to create self-contained objects that can be reused and
combined in different ways. This makes your code more modular and easier to maintain.
Security: Encapsulation allows you to control access to the internal data of an object, which can
improve the security of the system by preventing unauthorized access or modification of sensitive
data.
Flexibility: Encapsulation allows you to change the internal implementation of an object without
affecting the rest of the system. This makes your code more flexible and adaptable to changing
requirements.
Extensibility: Encapsulation allows you to create a stable and robust system, as it allows you to
add new features and functionality to the objects without affecting the existing code.
Encapsulation in C#:
In C#, encapsulation is achieved through the use of access modifiers, such as "private,"
"protected," and "internal."
"private" members of a class can only be accessed within the class itself.
"protected" members can be accessed within the class and any derived classes.
"internal" members can be accessed within the same assembly.
A fully encapsulated class has getter and setter functions that are used to read and write data. This
class does not allow data access directly.
}
}
public class Departmentmain {
public static void Main(string[] args)
{
Employeeemp = newEmployee();
emp.EmployeeName = "Mukesh Kumar";
Console.WriteLine("Employee Name is " + emp.EmployeeName);
}
}
In C#, we use Access Modifier to hide the data from the outer world. The following are the access
modifiers.
Private
It is used to restrict the member function or variable to be called outside from the class. If we
create any function or variable inside the class as private then it will not be accessible to
outside the class.
Public
A member function or variable declared as public can be accessed from outside the class. It
means you can access public member from anywhere.
Internal
The member functions and variables which are declared as Internal only can be accessible
inside the same namespace. You cannot access these members outside the namespace where
these are declared.
Protected
The Protected members can only be accessible from its child class or in same class. It is best
when you are using inheritance in your project.
ProtectedInternal
It can be accessible within the assembly where it is declared or in derived class of other
assembly.
Inheritance:
In C#, inheritance is a process in which one object acquires all the properties and behaviors of its
parent object automatically. In such way, you can reuse, extend or modify the attributes and
behaviors which is defined in other class.
In C#, the class which inherits the members of another class is called derived class and the class
whose members are inherited is called base class. The derived class is the specialized class for the
base class.
Acquiring (taking) the properties of one class into another is called inheritance. Code reusability
is one of the key features of OOPs, and it is achieved via inheritance. Using inheritance, one or
more classes can derive from an existing class. The existing class is called a base class, and the
inherited class is called a derived or inherited class.
The following are the types of inheritance in C#.
The inheritance concept is based on a base class and its derived classes. Let us see the definition
of base and derived classes.
Base class - the class from which features are to be inherited into another class.
Derived class - the class that is inherited from the base class.
Single inheritance in C#
It is the type of inheritance in which there is one base class and one derived class.
Hierarchical inheritance in C#
This is the type of inheritance in which there are multiple classes derived from one base class.
This type of inheritance is used when there is a requirement of one class feature that is needed in
multiple classes.
Multilevel inheritance in C#
When one class is derived from another, this type of inheritance is called multilevel inheritance.
Polymorphism in C#:
Polymorphism is a Greek word meaning "one name many forms." "Poly" means many, and
"morph" means forms. In other words, one object has many forms or has one name with multiple
functionalities. Polymorphism allows a class to have multiple implementations with the same
name. It is one of the core principles of Object Oriented Programming after encapsulation and
inheritance. In this article, you'll learn what polymorphism is, how it works, and how to implement
it in C#.
Types of Polymorphism
using System;
namespace DemoCsharp
{
class Program
{
public int Add(int num1, int num2)
{
return (num1 + num2);
}
public int Add(int num1, int num2, int num3)
{
return (num1 + num2 + num3);
}
Method overriding:
using System;
namespace DemoCsharp
{
class BaseClass
{
public virtual int Add(int num1, int num2)
{
return (num1 + num2);
}
}
class ChildClass : BaseClass
{
public override int Add(int num1, int num2)
{
if (num1 <= 0 || num2 <= 0)
{
Console.WriteLine("Values could not be less than zero or equals to zero");
Console.WriteLine("Enter First value : ");
num1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter First value : ");
num2 = Convert.ToInt32(Console.ReadLine());
}
return (num1 + num2);
}
}
class Program
{
static void Main(string[] args)
{
BaseClass baseClassObj;
baseClassObj = new BaseClass();
Console.WriteLine("Base class method Add :" + baseClassObj.Add(-4, 8));
baseClassObj = new ChildClass();
Console.WriteLine("Child class method Add :" + baseClassObj.Add(-3, 2));
Console.ReadLine();
}
}
}
Output:
Override keyword:
We generally use override with virtual. When we need to override the base class method into a
derived class then we use the override keyword.
using System;
namespace Polymorphism
class A
class B : A
class C : B
class Program
A a = new A();
B b = new B();
C c = new C();
a.Test();
b.Test();
c.Test();
a = new B();
a.Test();
b = new C();
b.Test();
Console.ReadKey();
Output:
A::Test()
B::Test()
C::Test()
B::Test()
C::Test()
C# Abstract:
Abstract classes are the way to achieve abstraction in C#. Abstraction in C# is the process to hide
the internal details and showing functionality only. Abstraction can be achieved by two ways:
1. Abstract class
2. Interface
Abstract class and interface both can have abstract methods which are necessary for abstraction.
Abstract Method
A method which is declared abstract and has no body is called abstract method. It can be
declared inside the abstract class only. Its implementation must be provided by derived classes.
For example:
C# Abstract class
In C#, abstract class is a class which is declared abstract. It can have abstract and non-abstract
methods. It cannot be instantiated. Its implementation must be provided by derived classes. Here,
derived class is forced to provide the implementation of all the abstract methods.
using System;
public abstract class Shape
{
public abstract void draw();
}
public class Rectangle : Shape
{
public override void draw()
{
Console.WriteLine("drawing rectangle...");
}
}
public class Circle : Shape
{
public override void draw()
{
Console.WriteLine("drawing circle...");
}
}
public class TestAbstract
{
public static void Main()
{
Shape s;
s = new Rectangle();
s.draw();
s = new Circle();
s.draw();
}
}
Output:
drawing ractangle...
drawing circle...
Garbage Collection in C# | .NET Framework:
Garbage collection is a memory management technique used in the .NET Framework and many
other programming languages. In C#, the garbage collector is responsible for managing memory
and automatically freeing up memory that is no longer being used by the application.
The garbage collector works by periodically scanning the application’s memory to determine
which objects are still being used and which are no longer needed. Objects that are no longer being
used are marked for garbage collection, and their memory is freed up automatically by the garbage
collector.
Some of the key features of the garbage collector in C# include:
1. Automatic memory management: With the garbage collector, developers don’t need to
worry about manually allocating or freeing up memory. The garbage collector takes care
of memory management automatically, which can help reduce the risk of memory leaks
and other issues.
2. Low impact on application performance: The garbage collector runs in the background and
typically has a low impact on application performance. However, in some cases, garbage
collection can cause brief pauses or slowdowns in the application, particularly when large
amounts of memory need to be freed up at once.
3. Generation-based collection: The garbage collector in C# uses a generation-based approach
to memory management. Objects are initially allocated in a “young” generation and are
moved to an “old” generation if they survive multiple garbage collection cycles. This
approach helps reduce the amount of time required for garbage collection, as most objects
are collected in the young generation.
4. Finalization: The garbage collector also provides support for finalization, which is a
process that allows objects to perform cleanup tasks before they are destroyed. Objects
with finalizers are moved to a separate finalization queue, which is processed by the
garbage collector after all other objects have been collected.
Automatic memory management is made possible by Garbage Collection in .NET Framework.
When a class object is created at runtime, a certain memory space is allocated to it in the heap
memory. However, after all the actions related to the object are completed in the program, the
memory space allocated to it is a waste as it cannot be used. In this case, garbage collection is
very useful as it automatically releases the memory space after it is no longer required.
Garbage collection will always work on Managed Heap and internally it has an Engine which
is known as the Optimization Engine. Garbage Collection occurs if at least one of multiple
conditions is satisfied. These conditions are given as follows:
If the system has low physical memory, then garbage collection is necessary.
If the memory allocated to various objects in the heap memory exceeds a pre-set threshold,
then garbage collection occurs.
If the GC.Collect method is called, then garbage collection occurs. However, this method
is only called under unusual situations as normally garbage collector runs automatically.
1. Marking Phase: A list of all the live objects is created during the marking phase. This is
done by following the references from all the root objects. All of the objects that are not
on the list of live objects are potentially deleted from the heap memory.
2. Relocating Phase: The references of all the objects that were on the list of all the live
objects are updated in the relocating phase so that they point to the new location where
the objects will be relocated to in the compacting phase.
3. Compacting Phase: The heap gets compacted in the compacting phase as the space
occupied by the dead objects is released and the live objects remaining are moved. All the
live objects that remain after the garbage collection are moved towards the older end of
the heap memory in their original order.
Generation 0 : All the short-lived objects such as temporary variables are contained in
the generation 0 of the heap memory. All the newly allocated objects are also generation
0 objects implicitly unless they are large objects. In general, the frequency of garbage
collection is the highest in generation 0.
Generation 1 : If space occupied by some generation 0 objects that are not released in a
garbage collection run, then these objects get moved to generation 1. The objects in this
generation are a sort of buffer between the short-lived objects in generation 0 and the
long-lived objects in generation 2.
Generation 2 : If space occupied by some generation 1 objects that are not released in
the next garbage collection run, then these objects get moved to generation 2. The objects
in generation 2 are long lived such as static objects as they remain in the heap memory
for the whole process duration.
Methods in GC Class
The GC class controls the garbage collector of the system. Some of the methods in the GC
class are given as follows:
GC.GetGeneration() Method: This method returns the generation number of the target
object. It requires a single parameter i.e. the target object for which the generation number is
required.
using System;
Output:
The generation number of object obj is: 0
GC.GetTotalMemory() Method: This method returns the number of bytes that are allocated
in the system. It requires a single boolean parameter where true means that the method waits
for the occurrence of garbage collection before returning and false means the opposite.
using System;
Console.WriteLine(
"The generation number of object obj is: "
+ GC.GetGeneration(obj));
Console.WriteLine("Total Memory:"
+ GC.GetTotalMemory(false));
}
}
Output:
Total Memory:4197120
The generation number of object obj is: 0
Total Memory:4204024
GC.Collect() Method : Garbage collection can be forced in the system using the GC.Collect()
method. This method requires a single parameter i.e. number of the oldest generation for which
garbage collection occurs.
using System;
Interfaces:
An interface in C# is a contract that defines a set of methods, properties, events, and indexers
that a class or struct must implement. Interfaces cannot be instantiated directly, but they can
be implemented by classes and structs. They are one of several tools for implementing object-
oriented design in C#.
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.
It is used to achieve multiple inheritance which can't be achieved by class. It is used to achieve
fully abstraction because it cannot have method body.
Its implementation must be provided by class or struct. The class or struct which implements
the interface, must provide the implementation of all the methods declared inside the interface.
Syntax
An interface in C# is created using the interface keyword. The syntax for defining an interface
in C# is:
interface MyInterface
{
void MyMethod();
string MyProperty { get; set; }
event EventHandler MyEvent;
}
To implement an interface in C#, you use the : symbol, followed by the name of the interface.
The syntax for implementing an interface is as follows:
class MyClass : MyInterface
{
public void MyMethod()
{
// implementation of MyMethod()
}
Example:
using System;
Output:
Woof!
Meow!
Use of Interfaces:
IComparable Interface:
Defines a generalized type-specific comparison method that a value type or class implements to
order or sort its instances. Comparing objects involves determining whether two objects are equal
or determining their relative ordering. Equality comparison checks whether two objects have the
same state, while ordering comparison determines which object comes before or after the other.
C#-
public interface IComparable
Example-
using System;
using System.Collections;
// Sort ArrayList.
temperatures.Sort();
Output:
2
7
16
17
31
37
58
66
72
95
ICloneable Interface:
Supports cloning, which creates a new instance of a class with the same value as an existing
instance.Cloning refers to the process of creating an exact copy of an existing object. In many
programming languages, objects are reference types, meaning that variables hold references to
objects rather than the objects themselves. When you assign one object variable to another, you're
creating another reference to the same object. Cloning allows you to create a new object that has
the same state as the original object but is distinct from it.
C#-
public interface ICloneable
using System;
class Program
{
static void Main()
{
string[] arr = { "Amit", "Nitin", "Ankit", "Sunny", "Rahul" };
string[] arrCloned = arr.Clone() as string[];
Console.WriteLine(string.Join(",", arr));
Console.WriteLine(string.Join(",", arrCloned));
Console.ReadLine();
}
}
Output:
Amit, Nitin, Ankit, Sunny,Rahul
Unit no- 04
Introduction to ADO.NET And Windows Forms
Architecture of ADO.NET:
.NET Framework Data Providers
These are the components that are designed for data manipulation and fast access to data. It
provides various objects such as Connection, Command, DataReader and DataAdapter that are
used to perform database operations.
The DataSet
It is used to access data independently from any data resource. DataSet contains a collection of
one or more DataTable objects of data. The following diagram shows the relationship between
.NET Framework data provider and DataSet.
ADO.NET Framework Data Providers
Data provider is used to connect to the database, execute commands and retrieve the record. It is
lightweight component with better performance. It also allows us to place the data into DataSet to
use it further in our application.
The .NET Framework provides the following data providers that we can use in our application.
2. Creating Database
Now, create database by selecting database option then right click on it. It pops up an option menu
and provides couple of options.
Click on the New Database then it will ask for the database name. Here, we have created
a Student database.
Click on the Ok button then it will create a database.
3. Establish connection and create a table
After creating database, now, let's create a table by using the following C# code. In this source
code, we are using created student database to connect.
Program-
using System;
using System.Data.SqlClient;
namespace AdoNetConsoleApplication
{
class Program
{
static void Main(string[] args)
{
new Program().CreateTable();
}
public void CreateTable()
{
SqlConnection con = null;
try
{
// Creating Connection
con = new SqlConnection("data source=.; database=student; integrated security=S
SPI");
// writing sql query
SqlCommand cm = new SqlCommand("create table student(id int not null,
name varchar(100), email varchar(50), join_date date)", con);
// Opening Connection
con.Open();
// Executing the SQL query
cm.ExecuteNonQuery();
// Displaying a message
Console.WriteLine("Table created Successfully");
}
catch (Exception e)
{
Console.WriteLine("OOPs, something went wrong."+e);
}
// Closing the connection
finally
{
con.Close();
}
}
}
}
Output-
Retrieve Record
// Program.cs
using System;
using System.Data.SqlClient;
namespace AdoNetConsoleApplication
{
class Program
{
static void Main(string[] args)
{
new Program().CreateTable();
}
public void CreateTable()
{
SqlConnection con = null;
try
{
// Creating Connection
con = new SqlConnection("data source=.; database=student; integrated security=SSPI");
// writing sql query
SqlCommand cm = new SqlCommand("Select * from student", con);
// Opening Connection
con.Open();
// Executing the SQL query
SqlDataReader sdr = cm.ExecuteReader();
// Iterating Data
while (sdr.Read())
{
Console.WriteLine(sdr["id"] + " " + sdr["name"]+" "+sdr["email"]); // Displaying
Record
}
}
catch (Exception e)
{
Console.WriteLine("OOPs, something went wrong.\n"+e);
}
// Closing the connection
finally
{
con.Close();
}
}
}
}
Deleting Record
using System;
using System.Data.SqlClient;
namespace AdoNetConsoleApplication
{
class Program
{
static void Main(string[] args)
{
new Program().CreateTable();
}
public void CreateTable()
{
SqlConnection con = null;
try
{
// Creating Connection
con = new SqlConnection("data source=.; database=student; integrated security=SSPI");
// writing sql query
SqlCommand cm = new SqlCommand("delete from student where id = '101'", con);
// Opening Connection
con.Open();
// Executing the SQL query
cm.ExecuteNonQuery();
Console.WriteLine("Record Deleted Successfully");
}
catch (Exception e)
{
Console.WriteLine("OOPs, something went wrong.\n"+e);
}
// Closing the connection
finally
{
con.Close();
}
}
}
}
Program:
using System.Data.SqlClient;
namespace AdoNetConsoleApplication
{
class Program
{
static void Main(string[] args)
{
new Program().Connecting();
}
public void Connecting()
{
using (
// Creating Connection
SqlConnection con = new SqlConnection("data source=.; database=student; inte
grated security=SSPI")
)
{
con.Open();
Console.WriteLine("Connection Established Successfully");
}
}
}
}
Output:
//The Fill method will open the connection, fetch the data, fill the data in
//the data table and close the connection automatically
adapter.Fill(dataTable);
Console.ReadKey();
}
}
}
The user can bind values to the respective controls in ADO.NET. Depending on the type of
binding offered, they are distinguished as follows:
The Simple Data Binding is the process of binding the control with the single value in the
dataset. The controls like text box, label can be bound to the control through the control
properties.
Consider an example to display the result of the students in an examination. The details are
added in the following format.
1. Create a Windows Form Application in Visual Studio .NET. The following customized
format is created for user.
2. Once the design of the form is created, select the View option from the menu bar. Click on
the Properties window.
3. Select the first text box and the properties for it appear in the window.
4. Expand the DataBindings property
5. Select the Text property for enabling the drop down list.
6. Click the Add Project Data Source from the drop down list
7. Make a connection with the CurrentInfo database and select the Student table
8. Select the Other Data Sources, Project Data Sources, CurrentInfoDataSet, Student table.
9. Select the Name column and bind it with the textbox.
10. Bind all the other text boxes with the database values.
11. Press F5 and execute the Windows Form.
12. The following output is displayed to the user.
The Complex Data Binding is the process of binding the component with the Database. The
controls can be GridView, Dropdown list, or combo box. Multiple values can be displayed from
the dataset through the binding.
The controls that can be used for binding the multiple values from the database to the Windows
Form are listed below.
1. DataGridView: It is used to display the multiple records and columns. The DataSource
property of the DataGridView control is used for binding the specific data element.
2. ComboBox: The control contains a text box for entering the data and drop down list for
displaying the values. The DataSource property is useful for binding the control. The
element specific information can be bind through the DisplayMember property
3. ListBox: It is used for displaying the data for the column from several records of datasets.
The DataSource property is used for binding the control to the data source.
4. The DisplayMember property is used for binding the control to the specific data element.
Navigating Records in ADO.NET
A BindingNavigator control is used for handling the binding to the data source through the
pointer to the current item in the list of records.
The navigator control is used with the BindingSource control for enabling the users to navigate
the data records on a form. It provides a layer between the controls and windows form of the data
source. Users can navigate and modify the records in the Windows form.
The following figure displays the BindingNavigator control and the BindingSource control in the
Windows Form.
The Binding Navigator control has many controls for modifying the data source. The list of
controls and their functions are mentioned below:
1. Binding Navigator Add New Item Button: The + sign indicates that the new row can be
added to the data source.
2. Binding Navigator Delete Item Button: The X sign indicates that the current row can be
deleted from the data source.
3. Binding Navigator Move First Item Button: The button indicates that the user can move
to the first item in the data source.
4. Binding Navigator Move Last Item Button: The button indicates that the user can move
to the last item in the data source
5. Binding Navigator Move Next Item Button: The button indicates that the user can move
to the next item in the data source
6. Binding Navigator Move Previous Item Button: The button indicates that the user can
move to the previous item in the data source
7. Binding Navigator Position Item textbox: The returns current position in the data source
8. Binding Navigator Count Item Text box: The is used to return the total number of items
in the data source.
Consider the Order details table containing the data about the orders to be added. The data is
organized into a format as shown below:
1. Open Visual studio application and add Windows Forms Application from the template
pane.
2. Add the labels and a binding Navigator control, and textbox controls to the form
3. Click OK button
4. Click View, Properties Window, and open the Properties Window.
5. Add the appropriate names to the controls present in the web form.
6. Open the Data Source Configuration Wizard. The Database icon must be selected. Click
Next Button
7. Click New Connection Button. Add Connection dialog box is shown.
8. Add the Server Name, select Use SQL Server Authentication option from the Log on the
server section
9. Add the User name as sa and password as abcd1234
10. Select the Order Details database and click Test Connection button
11. Click OK and close the Add Connection dialog box
12. Click Next button. In the Choose Your Database Objects dialog box, expand Tables node.
13. Select the Orderdata table and click Finish button.
For binding the data to the control in the Windows Form, the following steps are executed.
1. 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.
2. 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.
3. 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.
Now drag and drop the controls that you needed on created Form. For example, if you can
add TextBox, ListBox, Button etc. as shown below. By clicking on the particular dropped
control you can see and change its properties present in the right most corner of Visual
Studio.
C# Windows Forms is a graphical user interface (GUI) framework that enables developers to
create desktop applications for the Windows operating system. Windows Forms applications
are created using the C# programming language and the .NET framework. They are built by
dragging and dropping controls such as buttons, text boxes, labels, and other user interface
elements onto a form.
1. The Windows Forms framework provides a rich set of controls that developers can use to
build applications with. These controls are designed to provide a consistent and familiar
user interface for Windows users. Developers can customize the appearance and behavior
of these controls by setting various properties and handling events.
2. To create a Windows Forms application in C#, you can use Microsoft Visual Studio, which
is an integrated development environment (IDE) that provides a visual designer to create
and layout the user interface elements. The visual designer is a drag-and-drop interface for
building your UI, and you can easily configure each control’s properties through a user-
friendly interface.
3. In addition to the visual designer, Visual Studio also provides a code editor that enables
developers to write the C# code for the application’s logic. Developers can handle events
and perform tasks such as data validation, data manipulation, and business logic
implementation.
4. Windows Forms applications are versatile and can be used to create various types of
applications such as data entry, management, and reporting applications, as well as games
and multimedia applications.
Resizing Menus:
In Windows Forms applications, resizing menus typically involves adjusting the layout of your
controls dynamically as the form size changes.
Anchor and Dock Properties: Ensure that your menu controls (like MenuStrip) and other controls
on the form are anchored or docked properly. This allows them to resize and reposition themselves
automatically when the form is resized.
Handling Form Resize Event: You can handle the Resize event of the form to adjust the size and
position of your menu controls accordingly. Here's a simple example in C#:
private void Form1_Resize(object sender, EventArgs e)
{
// Adjust the menu control position
menuStrip1.Width = this.Width;
Relative Sizing: Instead of setting absolute sizes for controls, you can use relative sizing
techniques. For example, you can set the menu width as a percentage of the form width, ensuring
that it scales appropriately.
Handling Menu Items: If you have dynamic menu items or menus, you may need to adjust their
size and position programmatically in response to the form's resize event.
Testing: After implementing the resizing logic, thoroughly test your application by resizing the
form to different sizes to ensure that the menu and other controls adjust correctly.
private void Form1_Resize(object sender, EventArgs e)
{
menuStrip1.Width = this.Width;
}
This code assumes that the Menu Strip control (named menuStrip1) is docked at the top of the
form and that you want it to resize horizontally with the form.
Differences between Windows Forms and Web Forms:
Technology:
Windows Forms: Windows Forms applications are designed to run on a local machine's operating
system (Windows). They provide a rich user interface that interacts directly with the user's
machine.
Web Forms: Web Forms applications are designed to run on a web server and are accessed through
a web browser. They use HTML, CSS, and JavaScript to render the user interface on the client-
side.
Deployment:
Windows Forms: Windows Forms applications are deployed as standalone executables that need
to be installed on each user's machine.
Web Forms: Web Forms applications are deployed on a web server and accessed through a browser
without the need for installation on user machines.
User Interface:
Windows Forms: Windows Forms provide a rich, desktop-like user interface with controls tailored
for desktop applications.
Web Forms: Web Forms provide a web-based user interface that works within the limitations of
web browsers and web technologies.
State Management:
Windows Forms: Windows Forms applications can store state on the local machine, such as in
registry settings or local files.
Web Forms: Web Forms applications need to manage state on the server-side or through client-
side mechanisms like cookies, session variables, or hidden fields.
Security:
Windows Forms: Windows Forms applications have access to the local file system and resources,
which can raise security concerns if not properly managed.
Web Forms: Web Forms applications run in a sandboxed environment within the browser, limiting
access to the user's system for security reasons.
Connectivity:
Windows Forms: Windows Forms applications can connect directly to local resources and
databases without the need for internet connectivity.
Web Forms: Web Forms applications need an internet connection to communicate with a web
server and access remote resources.
Cross-Platform Compatibility:
Windows Forms: Windows Forms applications are limited to Windows-based operating systems
and do not have native support for cross-platform deployment.
Web Forms: Web Forms applications can be accessed on any device with a web browser, making
them more cross-platform compatible.
Common controls:
1. Label: Displays text that the user cannot edit.
2. TextBox: Allows users to input text.
3. Button: Triggers an action when clicked.
4. DropDownList: Presents a list of options for users to select from.
5. CheckBox: Represents a single checkbox for users to toggle.
6. RadioButton: Allows users to select a single option from a group.
7. GridView: Displays tabular data with options for sorting, paging, and editing.
8. ListView: Similar to the GridView but offers more flexibility in design.
9. Repeater: A basic control for repeating a template at runtime.
10. FileUpload: Enables users to upload files to the server.
11. Image: Displays an image on the web page.
12. HyperLink: Renders a hyperlink that users can click to navigate to another page.
13. Calendar: Provides a calendar for date selection.
14. Validator Controls (e.g., RequiredFieldValidator, RegularExpressionValidator):
Validates user input based on specified criteria.
15. DropDownMenu: Displays a hierarchical menu of items for navigation.
These controls help you build interactive and user-friendly web applications in ASP.NET Web
Forms. They provide a wide range of functionality, from basic text input to complex data
presentation and validation mechanisms.
ASP.NET:
It is a web framework designed and developed by Microsoft. It is used to develop websites,
web applications and web services. It provides fantastic integration of HTML, CSS and
JavaScript. It was first released in January 2002. It is built on the Common Language Runtime
(CLR) and allows programmers to write code using any supported .NET language.
ASP.NET provides three development styles for creating web applications:
1. Web Forms
2. ASP.NET MVC
3. ASP.NET Web Pages
Web Forms
It is an event driven development framework. It is used to develop application with powerful
data access. It provides server side controls and events to create web application. It is part of
the ASP.NET framework. We will discuss it further in next chapters.
ASP.NET MVC
It gives us a MVC (Model View Controller), patterns-based way to build dynamic websites. It
enables a clean separation of concerns and that gives you full control over markup for
enjoyable, agile development. It also provides many features that enable fast development for
creating outstanding applications. We will discuss it further in next chapters.
In ASP.NET, a web page has execution lifecycle that includes various phases. These phases
include initialization, instantiation, restoring and maintaining state etc. it is required to
understand the page lifecycle so that we can put custom code at any stage to perform our
business logic.
Page Request: When the user requests a page, the server checks the request and then
compiles the page.
Page Start: In this phase, the two steps are carried out first is "request" and second
is"response". The request holds all information from the page.
Page Initialization: In this phase, all the controls on the page are set, and each has a
particular ID, and themes are applied to the pages.
Page Load: In Page Load, all the control properties are loaded, and information is set using
view state and control state.
Validation: The validation happens when the page execution goes successful it returns
true else the execution fails it returns false.
Event Handling: This happens in response to validation. In this case, the page is loaded
again. So, the postback event handler is called.
Rendering: It occurs before all the response information is sent to the user. It also stores
all the information sent to the user.
Unload: This phase helps to clean all the unwanted information. And it also cleans the
memory once the page output is sent to the user.
PreInit: It is the first event in the page life cycle. And it checks the IsPostBack property
and determines whether the page is a postback. It sets the themes and master pages, creates
dynamic controls, and gets and sets profile property values. The PreInit event can be
handled by overloading the OnPreInit method.
Init: This event is used to initialize the control property and the control tree is built. The
Init event can be handled by overloading the OnInit method or creating a Page_Init handler.
InitComplete: This event allows tracking of the view state. And it controls turn-on view-
state tracking. The InitComplete event can be used to make changes in ViewState.
PreLoad: This event is raised when the page loads the ViewState. And it Loads the
PostBack data.
Load: The page's load event is raised first, followed by recursively raising all child
controls' load events. The control tree's controls are made. The OnLoad method can be
overloaded to handle this event, or a Page Load handler can be made.
Control Events: It is used to handle specific control events such as Button control' Click
event.
LoadComplete: LoadComplete event occurs at the end of the event-handling stage. We
can use this event for tasks that require all other controls on the page to be loaded.
PreRender: This event takes place just before the output is rendered. By handling this
event, pages, and controls can perform any updates before the output is rendered. This
event occurs after the page object has created all controls that are required in order to render
the page.
PreRenderComplete: This event is triggered recursively for all child controls, make sure
that the pre-rendering phase is completely done. This event happens once each data-bound
control with its DataSourceID property set calls the DataBind method.
SaveStateComplete: The SaveStateComplete is raised after the view state and the control
state have been saved for the page and for all controls.
Render: This is not an event; rather, the Page object calls this method on each control at
this step of processing.
Unload: This is the last event and it is raised for each control and then for the page. It can
be handled by modifying the On UnLoad method.
ASP.NET Web Forms:
Web Forms are web pages built on the ASP.NET Technology. It executes on the server and
generates output to the browser. It is compatible to any browser to any language supported by
.NET common language runtime. It is flexible and allows us to create and add custom controls.
We can use Visual Studio to create ASP.NET Web Forms. It is an IDE (Integrated Development
Environment) that allows us to drag and drop server controls to the web forms. It also allows us to
set properties, events and methods for the controls. To write business logic, we can choose any
.NET language like: Visual Basic or Visual C#.
Web Forms are made up of two components: the visual portion (the ASPX file), and the code
behind the form, which resides in a separate class file.
ASP.NET provides various controls like: server controls and HTML controls for the Web
Forms.
HTML Controls:
These controls render by the browser.
Master Pages
It allowsus to create a consistent layout for the pages in our application. This page defines the look
and feel and standard behavior that we want for all of the pages in our application. When users
request the content pages, they merge with the master page to produce output that combines the
layout of the master page with the content from the content page.
Membership
Project's Account folder contains the files that implement the various parts of membership:
registering, logging in, changing a password, and authorizing access. Additionally, ASP.NET Web
Forms supports OAuth and OpenID. These authentication enhancements allow users to log into
your site using existing credentials, from such accounts as Facebook, Twitter and Google.
Routing
We can configure URL routing of our application. A request URL is simply the URL a user enters
into their browser to find a page on our web site. We use routing to define URLs that are
semantically meaningful to users and that can help with search-engine optimization (SEO).
State Management
ASP.NET Web Forms includes several options that help you preserve data on both a per-page
basis and an application-wide basis.
Security
Developing a secure application is most important aspect of software development process.
ASP.NET Web Forms allow us to add extensibility points and configuration options that enable
us to customize various security behaviors in the application.
Performance
Web Forms provides good performance and allows us to modify performance related to page and
server control processing, state management, data access, application configuration and loading,
and efficient coding practices.
Difference between asp.net controls and html controls:
The main difference between ASP.NET controls and HTML controls lies in how they are created
and rendered in a web application:
ASP.NET Controls:
Server-side Controls:
ASP.NET controls are server-side controls that are created and manipulated on the server.
They provide a higher level of abstraction and are easier to work with in the code-behind file.
Event-Driven Model:
ASP.NET controls have built-in event-handling mechanisms that make it easy to respond to user
interactions, such as button clicks.
Events are handled on the server-side, simplifying interaction with the control.
ViewState Support:
ASP.NET controls automatically maintain their state across postbacks using ViewState.
This allows for easier management of control states and data preservation.
Rich Functionality:
ASP.NET controls come with rich functionality out of the box, such as validation controls, data
binding controls, and user interface controls like GridView and Repeater.
HTML Controls:
Client-side Controls:
HTML controls are client-side controls that are rendered directly in HTML markup.
They are lightweight and do not provide the same level of functionality and ease of interaction as
ASP.NET controls.
Limited Functionality:
HTML controls are basic input elements like <input> , <button> , <select> , and <textarea> .
They typically do not have built-in event-handling mechanisms or advanced features like data
binding.
Direct Markup:
HTML controls are directly represented in HTML markup and are manipulated using client-side
JavaScript or other client-side technologies.
They require more manual coding compared to ASP.NET controls.
No View State:
HTML controls do not have built-in mechanisms for maintaining state across postbacks like
ASP.NET controls.
State management needs to be handled manually using techniques like hidden fields or client-side
storage.
ASP.NET State Management:
State Management is a process by which state and page information is maintained over multiple
requests for same or different pages. As HTTP is a stateless protocol, server does not store any
information once the
response is sent back to client based on his request. When user submits request again, the server
treats it as a new user. This is called stateless model. This model was workable when static web
sites were developed and hosted in the past. Now, with interactive web sites or dynamic web site,
there is a need to preserve some information to identify user, interact with user again and again
within same session and same application. This concept is known as Stateful protocol. The
information can be related to user, data objects, web pages or server objects.
ASP.NET provides facility to save information on server side as well as in client side. The
following options are available in Server Side State Management.
o Application State: Application state allows saving of data at application level which is
accessible throughout the life of an application. The life of application starts when IIS is
started and ends when IIS is stopped.
o Session State: The session state persists till the user is active or session time expires. When
a user submits request, a session is started. The session gets over either when time expires
or user explicitly abandons the sessions. The required information can be saved in session
for later user by same user within the same application.
o Profile Properties: This option also allows saving of user specific data. It is similar to
Session state except the data stored in Profile state never expires on use this property, the
SQLProfileProvider class needs to be configured. It allows storing of data in SQL database.
Since data is stored in database and not in application memory, therefore there is no risk of
losing data even if IIS is restarted again and again.
o Cache: Caching is a technique by which frequently used data and web pages are stored in
cache so that repeated cost of retrieval can be avoided. Storing frequently used data in
cache ensures high availability, improved performance and scalability. Cache is object of
System.Web Caching Cache class. The main disadvantage of using Cache is that it is
unreliable. The previously stored data stored in cache is deleted automatically to meet
memory requirement of current process.
Client Side State Management Options
The options available in client side state management help in storing information either in the page
or at the client computer. No information is stored at server side. The followings options are used
for client side state management.
o View State: View state provides facility to preserve page and values of controls at the
client side. The information is stored after post back. Post back is a request from user for
the page which is not for the first time. If value of IsPostBack property is true, it means
page is not requested for the first time. The view state can be at page level, application
level, machine level and control level. In page level state management, as long as the user
is on current page, the information is retained. Whenever user submits form, the current
state of page and controls are hashed into a string and saved in hidden field of the page.
More than one hidden field can be used if data exceed limit set
by MaxPageStateFieldLength property. When page is sent to server, the page parses the
view state string and restores the information. This is default mechanism. The view state
can be disabled at any stage. The property EnableViewState="false" is used in code when
it is required to disable view state
The demonstrate the concept of view state option, consider an ASP.NET project haring one ben
Each time a button is clicked, it displays the number of times the button is clicked.
o Control State: This is another client side state management option. This is used when
there is a need to store control data related to Custom control. View state can be disabled
but control state cannot be disabled.
o Hidden Field State: ASP.NET allows storing information in a hidden field which is a
server control and can be used to store information at page level. The value of the hidden
field is sent to HTTP form collection along with value of other controls. The hidden file
can be created in source file as given below.<input type="hidden" id="username"
name="username" value=""
This hidden field can be accessed in code behind file as given below. Dim st as String = Request
QueryString("username")
o Cookies: Cookie is a small amount of information that is stored in client machine.
o QueryString: A QueryString contains the information that is sent to server with URL.
- You can make layout changes of the site in the master page instead of making changes in the
pages.
- It provides an object model which allows you to customize the master page from individual
content pages.
- It allows you to centralize the common functionality of your pages so that you can make
updates in just one place.
- It defines placeholders for the content, which can be overridden by the content pages.
- When users request the content page, ASP.NET merges the layout of the master page with the
content of the content page and produce output.
2. Scalability: ASP.NET applications can easily scale to accommodate increased user loads
and data volume. It provides features like caching, session state management, and
application pooling to optimize performance.
Disadvantages:
Platform Dependency: ASP.NET applications are primarily designed to run on Windows servers,
which may limit deployment options for developers who prefer other platforms like Linux or
macOS.
Cost: While ASP.NET itself is free and open-source, developers may incur costs associated with
licensing fees for development tools like Visual Studio and server hosting fees for Windows
servers.
Steep Learning Curve: ASP.NET has a steep learning curve, especially for beginners with limited
experience in web development or Microsoft technologies. Developers may require time and
resources to acquire proficiency in ASP.NET development.
Vendor Lock-In: Since ASP.NET is a Microsoft product, developers may face vendor lock-in,
making it challenging to migrate to alternative platforms or technologies in the future.
Performance Overhead: While ASP.NET offers excellent performance and scalability, it may
introduce some performance overhead compared to lightweight frameworks or languages like
Node.js or PHP, especially for simple or static content.
Server-side scripting is a programming technique for creating code that may run software on the
server side. In other words, server-side scripting is any scripting method that may operate on a web
server. At the server end, actions such as website customization, dynamic changes in website
content, response creation to user requests, database access, and many more are carried out.
The server-side is made up of three parts: the database, the server, the APIs, and the backend web
software written in the server-side scripting language. When a browser requests a page with server-
side scripting, the web server evaluates the script before delivering the page to the browser. In this
case, script processing may entail collecting information from a database, performing simple
computations, or selecting the relevant material to be shown on the client end. The output is
provided to the web browser when the script is processed. The web server hides the scripts from
the end user until the content is delivered, making the data and source code safer.
Client-side scripting generates code that may be executed on the client end without needing
server-side processing. These scripts are typically embedded into HTML text. Client-side scripting
may be utilized to check the user's form for problems before submitting it and to change the content
based on the user input. The web needs three components to function: client, database, and server.
The client-side scripting may significantly reduce server demand. It is intended to be utilized as a
scripting language with a web browser as the host program. The HTML and CSS are delivered as
plain text when a user uses a browser to request a webpage from the server, and the browser
understands and renders the web content at the client end.