Now that we know some basics of .NET, let us see what makes .NET a wonderful
platform for developing modern applications.

• Rich Functionality out of the box


.NET framework provides a rich set of functionality out of the box. It contains
hundreds of classes that provide variety of functionality ready to use in your
applications. This means that as a developer you need not go into low level details
of many operations such as file IO, network communication and so on.

• Easy development of web applications


ASP.NET is a technology available on .NET platform for developing dynamic
and data driven web applications. ASP.NET provides an event driven
programming model (similar to Visual Basic 6 that simplify development of web
pages (now called as web forms) with complex user interface. ASP.NET server
controls provide advanced user interface elements (like calendar and grids) that
save lot of coding from programmer’s side.

• OOPs Support


The advantages of Object Oriented programming are well known. .NET provides
a fully object oriented environment. The philosophy of .NET is – “Object is
mother of all.” Languages like Visual Basic.NET now support many of the OO
features that were lacking traditionally. Even primitive types like integer and
characters can be treated as objects – something not available even in OO
languages like C++.

• Multi-Language Support


Generally enterprises have varying skill sets. For example, a company might have
people with skills in Visual Basic, C++, and Java etc. It is an experience that
whenever a new language or environment is invented existing skills are outdated.
This naturally increases cost of training and learning curve. .NET provides
something attractive in this area. It supports multiple languages. This means that
if you have skills in C++, you need not throw them but just mould them to suit
.NET environment. Currently four languages are available right out of the box
namely – Visual Basic.NET, C# (pronounced as C-sharp), Jscript.NET and
Managed C++ (a dialect of Visual C++). There are many vendors that are
working on developing language compilers for other languages (20+ language
compilers are already available). The beauty of multi language support lies in the
fact that even though the syntax of each language is different, the basic
capabilities of each language remain at par with one another.

• Multi-Device Support


Modern lift style is increasingly embracing mobile and wireless devices such as
PDAs, mobiles and handheld PCs. . . .NET provides promising platform for
programming such devices. .NET Compact Framework and Mobile Internet
Toolkit are step ahead in this direction.

• Automatic memory management


While developing applications developers had to develop an eye on system
resources like memory. Memory leaks were major reason in failure of
applications. .NET takes this worry away from developer by handling memory on
its own. The garbage collector takes care of freeing unused objects at appropriate
intervals.

• Compatibility with COM and COM+


Before the introduction of .NET, COM was the de-facto standard for
componentized software development. Companies have invested lot of money and
efforts in developing COM components and controls. The good news is – you can
still use COM components and ActiveX controls under .NET. This allows you to
use your existing investment in .NET applications. .NET still relies on COM+ for
features like transaction management and object pooling. In fact it provides
enhanced declarative support for configuring COM+ application right from your
source code. Your COM+ knowledge still remains as a valuable asset.

• No more DLL Hell


If you have worked with COM components, you probably are aware of “DLL
hell”. DLL conflicts are a common fact in COM world. The main reason behind
this was the philosophy of COM – “one version of component across machine”.
Also, COM components require registration in the system registry. .NET ends this
DLL hell by allowing applications to use their own copy of dependent DLLs.
Also, .NET components do not require any kind of registration in system registry.

• Strong XML support


Now days it is hard to find a programmer who is unaware of XML. XML has
gained such a strong industry support that almost all the vendors have released
some kind of upgrades or patches to their existing software to make it “XML
compatible”. Currently, .NET is the only platform that has built with XML right
into the core framework. .NET tries to harness power of XML in every possible
way. In addition to providing support for manipulating and transforming XML
documents, .NET provides XML web services that are based on standards like
HTTP, XML and SOAP.

• Ease of deployment and configuration


Deploying windows applications especially that used COM components were
always been a tedious task. Since .NET does not require any registration as such,
much of the deployment is simplified. This makes XCOPY deployment viable.
Configuration is another area where .NET – especially ASP.NET – shines over
traditional languages. The configuration is done via special files having special
XML vocabulary. Since, most of the configuration is done via configuration files,
there is no need to sit in front of actual machine and configure the application
manually. This is more important for web applications; simply FTPing new
configuration file makes necessary changes.

• Security


Windows platform was always criticized for poor security mechanisms. Microsoft
has taken great efforts to make .NET platform safe and secure for enterprise
applications. Features such as type safety, code access security and role based
authentication make overall application more robust and secure.
The next layer up in the framework is called the .NET Class Framework also referred
as .NET base class library. The .NET Class Framework consists of several thousand
type definitions, where each type exposes some functionality. All in all, the CLR and
the .NET Class Framework allow developers to build the following kinds of
applications:

• Web Services. Components that can be accessed over the Internet very easily.

• Web Forms. HTML based applications (Web Sites).

• Windows Forms. Rich Windows GUI applications. Windows form applications can
take advantage of controls, mouse and keyboard events and can talk directly to
the underlying OS.

• Windows Console Applications. Compilers, utilities and tools are typically
implemented as console applications.

• Windows Services. It is possible to build service applications controllable via the
Windows Service Control Manager (SCM) using the .NET Framework.

• Component Library. .NET Framework allows you to build stand-alone components
(types) that may be easily incorporated into any of the above mentioned
application types.

The Common Language Runtime (CLR)........

At the base is the CLR. It is considered as the heart of the .NET framework. .NET
applications are compiled to a common language known as Microsoft Intermediate
Language or “IL”. The CLR, then, handles the compiling the IL to machine language,
at which point the program is executed.
The CLR environment is also referred to as a managed environment, in which
common services, such as garbage collection and security, are automatically
provided.
More information on CLR is available at

The next layer up in the framework is called the .NET Class Framework also referred
as .NET base class library. The .NET Class Framework consists of several thousand
type definitions, where each type exposes some functionality. All in all, the CLR and
the .NET Class Framework allow developers to build the following kinds of
applications:

• Web Services. Components that can be accessed over the Internet very easily.

• Web Forms. HTML based applications (Web Sites).

• Windows Forms. Rich Windows GUI applications. Windows form applications can
take advantage of controls, mouse and keyboard events and can talk directly to
the underlying OS.

• Windows Console Applications. Compilers, utilities and tools are typically
implemented as console applications.

• Windows Services. It is possible to build service applications controllable via the
Windows Service Control Manager (SCM) using the .NET Framework.

• Component Library. .NET Framework allows you to build stand-alone components
(types) that may be easily incorporated into any of the above mentioned
application types.

The Common Language Runtime (CLR)........

At the base is the CLR. It is considered as the heart of the .NET framework. .NET
applications are compiled to a common language known as Microsoft Intermediate
Language or “IL”. The CLR, then, handles the compiling the IL to machine language,
at which point the program is executed.
The CLR environment is also referred to as a managed environment, in which
common services, such as garbage collection and security, are automatically
provided.
More information on CLR is available at

When compiling to managed code, the compiler translates your source code into
Microsoft intermediate language (MSIL), which is a CPU-independent set of
instructions that can be efficiently converted to native code. MSIL includes
instructions for loading, storing, initializing, and calling methods on objects, as well
as instructions for arithmetic and logical operations, control flow, direct memory
access, exception handling, and other operations. Before code can be executed, MSIL
must be converted to CPU-specific code by a just in time (JIT) compiler. Because the
runtime supplies one or more JIT compilers, for each computer architecture it
supports, the same set of MSIL can be JIT-compiled and executed on any supported
architecture.
When a compiler produces MSIL, it also produces metadata. The MSIL and metadata
are contained in a portable executable (PE file) that is based on and extends the
published Microsoft PE and Common Object File Format (COFF) used historically for
executable content. This file format, which accommodates MSIL or native code as
well as metadata, enables the operating system to recognize common language
runtime images. The presence of metadata in the file along with the MSIL enables
your code to describe itself, which means that there is no need for type libraries or
Interface Definition Language (IDL). The runtime locates and extracts the metadata
from the file as needed during execution.
To start of with any language it’s always worth writing a simple program, which actually
does nothing but displays a “HelloWorld” string in the screen. Taking this simple
program we will try to figure out how .NET framework delivers a successful
HelloWorld.exe. Well to write such a complex program we will go for our favorite editor,
the choice is unanimous, it’s “Notepad”.



'This is the famous HelloWorld Program written using VB.NET
Namespace HelloWorldSample
'Definition of the Class
Public Class HelloWorld
'entry point method for the Class
Public Shared Sub Main()
System.Console.WriteLine("HelloWorld")
End Sub
'end of Class Declaration
End Class
'end of the Class Module
'end of namespace
End Namespace
Now let us spend sometime in examining the HelloWorld program to find out what’s new
in writing code through any .NET language.

The lines in the program that starts with a ‘(single quote) are comment entries like in
other programming languages which are excluded in the compilation process. Like VB
the way in which comment entries are represented remains the same in VB.NET.
Namespace HelloWorldSample - The keyword “Namespace” is new to some
programmers who are not familiar with C++.

‘Namespace’ – a keyword in .NET is used to avoid name collisions i.e. For example, you
develop a library which has a class named “File” and you use some other library which
also has a class named “File”, in those cases there are chances of name collision. To
avoid this you can give a namespace name for your class, which should be meaningful. It
is always better to follow the syntax (MS Recommended) given below while giving
names for your namespaces

CompanyName.TechnologyName

However the hierarchy can be extended based on the implementation of the classes in the
library.

Public Class HelloWorld - This is the class declaration in VB.NET; the interesting thing
for VB developers is that VB.NET is a fully object-oriented language (so everything is a
Class here) . The class always ends with an “End Class”.

‘Public’ - is the modifier to determine the scope of the class (for other modifiers refer
.NET framework SDK documentation or later parts of this tutorial). HelloWorld is the
class name given for the class. Consumers of the class will be accessing through this
name only

Public Shared Sub Main () - This is called as the entry point function because the
runtime after loading your applications searches for an entry point from which the actual
execution starts. C/C++ programmers will find this method very familiar (VB
Programmers remember Sub Main). All Applications (exe) must have a definition for the
Main Method. Try removing the Main method from your application and the compiler
will complain that "No Start Point Defined". This means that the Main Method is the
starting point of any application, in other words When you execute your Application
"Main" method is called first automatically.

'Public' - This is the Access modifier for the Method. Since the Main method should be
accessible to everyone in order for the .NET Runtime to be able to call it automatically it
is always defined as public.

'Shared' - indicates that the method is a Class Method. Hence it can be called without
making an instance of the class first.

Now its time to compile and execute this complex program. To compile the above piece
of code you can use VB.NET compiler. To run the VB.NET compiler make sure you set
your path variable to point to the place where your VB.NET compiler is available. (To
set a new value in the path variable, go to control panel and double click System icon,
then choose advanced tab and click Environment Variables button to add or edit the
environmental variables)

Figure shows compilation of the HelloWorld program for VB.NET
The compiler used here is “vbc”, which is a visual basic .net compiler accepts the source
file “HelloWorld.vb” compiles the same to produce a program that’s not true executable,
instead it generates something called assembly. Here the VB.NET compiler produces a
Managed Code/Intermediate Language (MSIL) format that uses instructions which are
CPU-independent.
/* This is the famous helloworld program written using C#.NET */
/* Indicates that the code is referring System Namespace to access the
functionality’s of System.dll */
using System;
// Namespace name given for the class
namespace HelloWorldSample
{
//Definition of the class
public class HelloWorld
{
// Entry point method for the class
public static void Main()
{
//Displaying helloworld in the screen
System.Console.WriteLine("HelloWorld");
}
//end of the class declaration
}
//end of the namespace
}
Figure showing HelloWorld program written using C#.NET in Notepad
The lines in the program that starts with a // and /*….*/ (comment blocks) are comment
entries like in other programming languages which are excluded in the compilation
process. For C or C++ programmers the C# style of coding sounds great because it
almost follows the same style.

namespace HelloWorldSample - The keyword “namespace” is new to some
programmers who are not familiar with C++.

‘namespace’ – a keyword in .NET is used to avoid name collisions i.e. For example, you
develop a library which has a class named “File” and you use some other library which
also has a class named “File”, in those cases there are chances of name collision. To
avoid this you can give a namespace name for your class, which should be meaningful. It
is always better to follow the syntax (MS Recommended) given below while giving
names for your namespaces
CompanyName.TechnologyName
However the hierarchy can be extended based on the implementation of the classes in the
library.

public class HelloWorld - This is the class declaration in C#.NET; the interesting thing
for C++ or Java developers is that they can apply the OOPS concepts that are supported
by C#.NET . The class always ends with an “End Class”.

‘public’ - is the modifier to determine the scope of the class (for other modifiers refer
.NET framework SDK documentation or later parts of this tutorial). HelloWorld is the
class name given for the class. Consumers of the class will be accessing through this
name only.

public static void Main () - This is called as the entry point function because the runtime
after loading your applications searches for an entry point from which the actual
execution starts. C/C++ programmers will find this method very familiar (VB
Programmers remember Sub Main). All Applications (exe) must have a definition for the
Main Method. Try removing the Main method from your application and the compiler
will complain that "No Start Point Defined". This means that the Main Method is the
starting point of any application, in other words When you execute your Application
"Main" method is called first automatically.

'public' - This is the Access modifier for the Method. Since the Main method should be
accessible to everyone in order for the .NET Runtime to be able to call it automatically it
is always defined as public.

'static' - indicates that the method is a Class Method. Hence it can be called without
making an instance of the class first.

‘void’ – indicates the return type of the Main function, here in this case the Main function
returns nothing so it is mentioned as void, for functions that returns value should have
appropriate type such as long, string etc.,

Now its time to compile and execute this complex program. To compile the above piece
of code you can use C# compiler. To run the C# compiler make sure you set your path
variable to point to the place where your C# compiler is available. (To set a new value in
the path variable, go to control panel and double click System icon, then choose
advanced tab and click Environment Variables button to add or edit the environmental
variables)

Figure shows compilation of the HelloWorld program using C# compiler
The compiler used here is “csc”, which is a visual basic .net compiler accepts the source
file “HelloWorld.cs” compiles the same to produce a program that’s not true executable,
instead it generates something called assembly.
Assembly
An assembly is a grouping of files deployed as a single file. An assembly almost always
consists of at least two files: the executable and the manifest. The manifest is a list of all
the files that exist inside the assembly. The executable content inside the assembly is
referred to individually as a module. Conceptually, modules correspond to DLLs or
EXEs; each module contains metadata, in addition to the metadata of its parent assembly.
The assembly format is an enhanced version of the current Portable Executable (PE)
format (your normal Windows .EXE file format).
Manifest
Manifest is considered as the integral part of every assembly that renders the assembly
self-describing. The assembly manifest contains the assembly's metadata and it also
establishes the assembly identity, specifies the files that make up the assembly
implementation, specifies the types and resources that make up the assembly, itemizes the
compile-time dependencies on other assemblies, and specifies the set of permissions
required for the assembly to run properly.
Metadata
The standard PE header comes at the beginning of the file. Inside the file is the CLR
header, followed by the data required to load the code into its process space—referred to
as metadata. It describes to the execution engine how the module should be loaded, what
additional files it needs, how to load those additional files, and how to interact with COM
and the .NET runtime.
Metadata also describes the methods, interfaces, and classes contained in the module or
assembly. The information the metadata provides allows the JIT compiler to compile and
run the module. The metadata section exposes much of your application's internals and
eases the transition from disassembled IL to useful code.

The .NET Runtime ships with a Just-In-Time (JIT or JITter) compiler, which will convert
the MSIL code in to the native code (CPU Specific executable code). So whatever code
we write will be complied in to MSIL format and the JIT takes over when you run it.
The .NET runtime/Common Language Runtime (CLR) ships three different classes of
JITters. The Main JIT compiler converts the MSIL code it to native code with out any
optimizations. The JIT compiler takes the MSIL code and optimizes it. So this compiler
requires lot of resources like, time to compile, larger memory footprint, etc. The PreJIT
is based on the Main JIT and it works like the traditional compilers (compiles MSIL to
native code during compilation time rather than runtime). This compiler is usually used at
the time of installation.
No matter whatever language we used to develop the HelloWorld program, it’s a known
fact that compiler’s are going to generate a MSIL format, once our code has been
converted in to MSIL format, from MSIL format all the code that we write will be
converted to native code in the same way whether if it is a VB.NET source or C# source.
.NET framework offers a myriad of languages which puts us programmers into a deep
thought process about which programming language best suits our needs.
Which language is the "best" language choice? If you are a VB wizard, should you take
the time to learn C# or continue to use VB.NET? Are C# ASP.NET pages "faster" than
VB .NET ASP.NET pages? These are questions that you may find yourself asking,
especially when you're just starting to delve into .NET. Fortunately the answer is simple:
there is no "best" language. All .NET languages use, at their root, functionality from the
set of classes provided by the .NET Framework. Therefore, everything you can do in
VB.NET you can do in C#, and vice-a-versa.
The differences occur in three main areas: syntax, object-oriented principles, and the
Visual Studio .NET IDE. Syntax concerns the statements and language elements. Object
Oriented differences are less obvious, and concern differences in implementation and
feature sets between the two languages. IDE differences include things like compiler
settings or attributes. There is also a fourth area of difference: language features that are
present in one language but have no equivalent in the other.
If you are more familiar with Java, JScript, or C/C++, you may find C#'s syntax more
familiar than VB.NET's.
A good question that has to be answered in order to keep you interested in learning C# is
Why should you learn another programming language when you already doing enterprise
development in C++ or Java. The very answer at the first go will be C# is intended to be
the premier language for writing NGWS (Next Generation of Windows Services)
applications in the enterprise computing world.
The programming language C# derives from C and C++; however apart from being
entirely object oriented it is type safe and simple too. If you are a C/C++ programmer
your learning curve should be flat. Many C# statements including expressions and
operators have been taken directly taken from your favourite language
An important point about C# is that it simplifies and modernizes C++ in the areas of
classes, namespaces and exception handling. Much of complex features have not been
included or in fact hidden in C# to make it easer to use and more importantly less error
prone for e.g. no more macros, templates and no multiple inheritances (Few of you might
not like it.)
C# provides you with convenient features like garbage collection, versioning and lot
more.
The only expense that I can think of is that your code operates in safe mode, where no
pointers are allowed. However if you want to use pointers you are not restricted from
using it via unsafe code- and no marshalling is involved when calling the unsafe code.
So you will learn a great deal of this new language in the coming Sections and see for
yourself that how C# resembles or not resembles your favorite language
Constants & Variables
A variable is a named memory location. They are programming elements that can change
during program execution. Data that needs to be stored in memory & accessed at a later
time are stored in variables. Instead of referring to the memory location by the actual
memory address you refer to it with a variable name.
Variables are declared as follows
int a;
They can also be initialized at the time of declaration as follows:
int a = 10;
Constants are very similar to variables. The main difference is that the value contained in
memory cannot be changed once the constant is declared. When you declare a constant
its value is also specified and this value cannot be changed during program execution.
Constants are used in situations where we need to keep the value in some memory
location constant. If you use hard-coded values, and the value is changed then it has to be
changed in all the locations in the code where it has been used. Instead if we are using
constants, all we will need to do is to change the value of the constant. This would
propagate the changes to our entire application.


Constants are declared as follows
const int a;
Simple Types (Primitive Data types)
Simple or value type variables are those, which are assigned space in the stack instead of
the heap. All the primitive types such as int, double etc are value type variables. The
simple types basically consist of Boolean and Numeric types, where Numeric is further
divided into Integral and Floating Point.

The first rule of value types is that they cannot be null. Anytime you declare a variable of
value type, you have allocated the number of bytes associated with that type on the stack
and are working directly with that allocated array of bits. In addition, when you pass a
variable of value type, you are passing that variable’s value and not a reference to the
underlying object.

Object Type
Object type or reference type variables are those, which are allocated storage space in the
heap. Reference type objects can be null. When a reference type is allocated under the
covers a value is allocated on the heap and a reference to that value is returned. There are
basically four reference types: classes, interfaces, delegates and arrays.

Class Type
Custom data types are available in .NET framework in the form of classes or class type. It
is nothing but a set of data and related behavior that is defined by the developer.

Object type and class type are both reference type variables. The only difference comes
from the fact that object type consists of objects predefined and available with the .NET
framework such as string whereas class type consists of custom user defined data types
such as the class employee given below.

class employee
{
int empid;
string empname
public employee()
{
empid = 10;
empname = “Reshmi”;
}
}
Class inheritance causes the methods and properties present in the base class also to be
derived into the derived class. A situation may arise wherein you would like to change
the functionality of an inherited method or property. In such cases we can override the
method or property of the base class. This is another feature of polymorphism.


public abstract class shapes
{
public abstract void display()
{
Console.WriteLine("Shapes");
}
}
public class square: shapes
{
public override void display()
{
Console.WriteLine("This is a square");
}
}
public class rectangle:shapes
{
public override void display()
{
Console.WriteLine("This is a rectangle");
}
}


Enumerations are types that inherit from System.Enum. The elements of an enumeration
are expressed in words rather than numbers, which makes it convenient for understanding
the meaning of the value being used. Enumerations symbolically represent a set of values
of one of the primitive integral types.
The type of the elements of an enumeration can be byte, short, int or long. If no type is
specified explicitly, the default type is int.

Example:
enum month : byte
{Jan = 2, Feb = 5, Mar = 10};


Explanation:
In the above code segment, an enumeration type month is declared. The underlying type
of the elements has been specified as byte. It has three elements viz: Jan, Feb and Mar.
These three elements have been assigned specific values. In case of an enumeration, if no
values are specified, the value of the first element corresponds to 0 and so on.
C# has statements such as if ….. else ….. and switch…case which help you to
conditionally execute program.
C# provides you with various looping statements, such as do… while, while, for and
foreach….in.

1. The if ….else….. Statement
Consider a student marks and grade evaluation. For Marks above 75 the grade is ‘A’ and
for below 75 is ‘B’. In this situation when you need to execute some code based on some
condition, you can make use of, if …. else …...
The Cultural syntax normally used is as follows:
if (condition)
{
Executable statements when the condition is True
}
else
{
Executable statements when the Condition is False
}
OR using else if for Advanced Decision making
if (condition)
{
Executable statements
}
else if (condition)
{
Executable statements
}
Single if can have multiple else if with conditions, as mentioned above in else if format.
Nesting if …else Constructs
if (condition)
{
if (condition)
{
Executable statements when the condition2 is TRUE
}
else
{
Executable Statements
}
else
{
Executable statements
}
One important thing to keep in mind when nesting if…else constructs is that you must have remember to close the
brace ({ }) for every brace that you open.

2. The switch…case Statement.
The switch statement is a control statement that handles multiple selections by passing
control to one of the case statements within its body.
The switch…case Statement is similar to if…else. The only difference between two is
that if and else if can evaluate different expressions in each statement, but the switch
statement can evaluate only one expression.
The drawback of if...else construct is that it isn’t capable of handling a decision situation
without a lot of extra work. One such situation is when you have to perform different
actions based on numerous possible values of an expression, not just True or False. For
instance performing actions based on Students Grade.
if ( Grade.Equals (“A”))
{
…….
}
else if (Grade.Equals (“B”))
{
……
}
else if (Grade.Equals (“C”))
{
……
}
else if (Grade.Equals (“D”))
{
……
}
else
{
.….
}
As you see the structure can be a bit hard to read and if the conditions increase you may
end up writing a confusing and an unreadable piece of Code
The switch uses the result of an expression to execute different set of statements.
The syntax for the select…case Statement is as follows:
switch (expression)
{
case constant-expression:
statement
jump-statement
default:
statement
jump-statement]
}
Notice that the jump-statement is required after each block, including the last block
whether it is a case statement or a default statement.
Note: default is used to define the code that executes only when the expression
doesn’t evaluate to any of the values in case Statements .Use of default case is
optional
Let’s see the same example as above but this time with switch case.
switch(grade)
{
case “A”:
Executable statements
jump-statement
case “B”:
Executable statements
jump-statement
case “C”:
Executable statements
jump-statement
case “D”:
Executable statements
jump-statement
default :
Executable statements
jump-statement
}
Branching is performed using jump statements, which cause an immediate transfer of the
program control.(break, continue, default ,goto ,return)
Evaluating More than one possible Value in a case Statement is not possible in C#,
but VB.Net does allow evaluating more than one Value.

3. for Statements.
The for loop executes a statement or a block of statements repeatedly until a specified
expression evaluates to false.

for ([initializers]; [expression]; [iterators]) statement


where:
Initializers: A comma separated list of expressions or assignment statements to initialize
the loop counters.
Expression : expression is used to test the loop-termination criteria.
Iterators : Expression statement(s) to increment or decrement the loop counters.

Example print numbers from 1 To 100
for (int intctr =1; intctr <= 100; intctr++)
Debug.WriteLine(intctr);


This routine starts a loop with a for statement after a variable intctr is declared. This loop
initializes intctr to 1 and then prints 1 through 100 to the output window.
Note: you can declare variable in the Initialization part of the for loop separated by
comma.

Example : print even number from 1 to 100
for(int i=2; i <= 100; i = i + 2)
Debug.WriteLine(i.ToString());
Example : To Sum the total of all number from 1 to 10
for( i =1 ; i < 11 ; i++)
sum = sum + i ;
Example : The statement below can be used as an infinite loop.
for ( ; ; );
Example of use of for loop.
Let us see how to a write table of 2 using for loop.
for(int j = 1,i = 2; j <= 10; j++)
Debug.WriteLine("2 X " + j.ToString() + " = " + i*j );
Output:
2 X 1 = 2
..
..
..
..
..

2 X 10 = 20
An Example of Nested For loop.
Let us write a small code to display a structure of stars ‘*’ in triangle format.
*
* *
* * *
* * * *
* * * * *
* * * * * *
Let us have a label with name stars. Increase the height of the label to get a clear view of
the image.

string star="";
for(int i = 0; i < 5 ;i++) // First loop to count the rows
{
for (int j = 0; j <= i; j++) // Second loop to count
the columns
{
star = star + " * ";
}
Debug.WriteLine(star);
star = "";
}


Note: For better readability you must always indent your
Codes.

4. foreach…in Statement
The foreach…in Statement is used to repeat a set of statements for each element in an
array or collection.
The foreach…in statement is executed if there is at least one item in an array of
collection. The Loop repeats of each element in an array or collection.
The syntax for the foreach…in statement as follows:

foreach (type Component in Set )
{
Executable statements
}


Component is the variable used to refer to the elements of an array or a collection.
Set refers to an array or any collection object.

e.g.
string[] weeks = {"Monday", "Tuesday", "Wednesday",
"Thursday",
"Friday", "Saturday", "Sunday"};
foreach(string eachday in weeks)
{
MessageBox.Show(eachday);
}


An example for using foreach element in a collection of string into a single string
element.
Each element of array which is of type string is read from the collection and stored into
the single string type object.

5. while…Statement


The while… Statement is used to repeat set of executable statements as long as the
condition is true.
The syntax for the while… statement is as follows:

while (Condition)
{
Executable Statements
}


In this if the condition is satisfied then the statements are executed. Else it will not enter
the while condition at all.
example of infinite loop is

while (true);
Example print numbers from 1 to 100
int i = 1;
while ( i <= 100)
{
Debug.WriteLine(i.ToString());
i++;
}


Example print even numbers from 1 to 100
Int i = 2;
While( i <=100)
{
Debug.WriteLine(i.ToString());
i = i + 2;
}


6. do...while Statement


The do...while Statement is similar to while… Statement.

do
{
Statements to Execute
}
while (condition)


example print numbers from 1 to 100
int i = 1;
do
{
Debug.WriteLine(i.ToString());
i++;
}while( i <= 100);
example print even numbers from 1 to 100
int i = 2;
do
{
Debug.WriteLine(i.ToString());
i = i + 2;
}while( i <= 100);


A Complete Example with set of control statements.

We will create a C# application, which will accept students name and its grade.
Depending upon the type of grade it will add remarks.

int value=0, ctr=0;
//Accept a number from the user
Console.Write("Enter the number of students : ");
value = Int32.Parse(Console.ReadLine());
string [] arrName= new string[value];
string sGrade ="";
string [] arrRemarks= new string[value];
while (ctr < value)
{
//Accept the name of the students
Console.Write("Enter the name of the Student" + (ctr +
1) + " : ");
arrName[ctr] = Console.ReadLine();
//Accept the grade of the Student
Console.Write("Enter the grade of the student
A/B/C/D/F : " );
sGrade = Console.ReadLine();
// Assign remarks to students
switch (sGrade.ToUpper())
{
case "A":
arrRemarks[ctr] = "Excellent";
break;
case "B":
arrRemarks[ctr] = "Good";
break;
case "C":
arrRemarks[ctr] = "Fair";
break;
case "D":
arrRemarks[ctr] = "Poor";
break;
case "F":
arrRemarks[ctr] = "Fail";
break;
default:
Console.WriteLine("Incorrect value entered
");
return; // To come out of the program
}
ctr = ctr + 1;
}
// Display the summary on the Console
for (ctr = 0 ;ctr< value; ctr=ctr+1)
{
if (arrRemarks[ctr].Equals("fail"))
{
Console.WriteLine(arrName[ctr] + " has failed in_
exams ");
}
else
{
Console.WriteLine(arrName[ctr] + "'s
performance is " + arrRemarks[ctr]);
}
}
Till now we have been using variable to store values. We might come across a situation
when we might need to store multiple values of similar type. Such as names of 100
students in a school. One way to do it is to declare 100 variables and store all the names.
A much more simple and efficient way of storing these variable is using Arrays. An
Array is a memory location that is used to store multiple values.
All the values in an array are of the same type, such as int or string and are referenced by
their index or subscript number, which is the order in which these values are stored in the
array. These values are called the elements of the array.
The number of elements that an array contains is called the length of the array.
In C# all arrays are inherited from the System.Array Class.
Arrays can be single or multidimensional. You can determine the dimensions of an array
by the number of subscripts that are used to identify the position of any array element.
A single dimensional array is identified by only a single subscript and an element in a
two-dimensional array is identified by two subscripts.
Arrays in C# also support the concept of Jagged Arrays.
The dimension has to be declared before using them in a program. The array declaration
comprises the name of the array and the number of elements the array can contain.


The Syntax of single dimension array is as follows.
Datatype [] ArrayName = new DataType[number of elements];
e.g.
string [] studentname = new string [5];



You can assign the values at runtime or even at the design time.
Design time declaration:

Studentname [0]=”Rohan”
Studentname [1]=”Mohan”
…..
Studentname[10]=”Nitin”


All arrays starts with the index of 0 i.e. All arrays are Zero Based. This implies that above
array can store 10 elements. Here 0, is the starting index or the lower bound of the array
and 9 is the upper bound while the length of the array is 10.

Example 1.
We will create a C# Console Application that will accept the names of students in an
single dimension array and display it back.

int value = 0, cnt = 0;
//Accept how many students names to enter
Console.Write("Enter the number of students name to enter:
");
value = System.Int32.Parse(Console.ReadLine()) ;
string[] arrnames = new string [value];
for(cnt = 0; cnt<value;cnt++)
{
Console.Write("Enter the name of student " + (cnt + 1)
+ ":", "Student Name");
arrnames[cnt] = Console.ReadLine();
}
Console.WriteLine("Pulling Values from the Array");
//Display the entered value to the text box
for(cnt = 0; cnt < value; cnt++)
{
Console.WriteLine(arrnames[cnt]);
}


Above example will accept number of names to be entered and will add the names in a
loop and then redisplay it on the Console. Note that we have not written any error
handling code that is left to the reader as an exercise.
The Syntax for multi-dimension arrays is as follows:
Previously we saw how we can store multiple names of students. But, if we want to store
related data of students like first name, middle name, last name. In such situations you
can use multi dimension arrays, such as two-or-three dimension arrays.
Datatype [] ArrayName = new Datatype[number of 1st element,
number of 2nd element,….];
e.g.
string[,] studentdetails = new string [10,2];
Index positions of array elements.
0,0 0,1
1,0 1,1
2,0 2,1
3,0 3,1

10,0 10,1
studentdetails(0,0) = “Manoj”
studentdetails(0,1) = “Malik”
To display “Malik” we need to use the index position of the array and say ,
Studentdetails [0,1].

Example 2.
We will create a C# Console Application, which will accept Student Name, Address and
city name and display it on the Console.
string [,] arrsummary = new string[3, 3];
int i=0, j=0;
//As we wanted just 3 columns we have set it to 2, else if
u want to be two only then while declaring the array make
it (2,2) as the lower index is 0.
for(i = 0;i<=2;i++)
{
for(j = 0;j<=2;j++)
{
Console.WriteLine("Enter the value for " + i + "
row and " + j + " column, Summary");
arrsummary[i, j] = Console.ReadLine();
}
}
Console.WriteLine();
//Display the values in the summary array.
for(i = 0;i<=2;i++)
{
string s = "";
for(j = 0;j<=2;j++)
{
if (s.Equals(""))
{
s = arrsummary[i, j];
}
else
{
s = s + " - " + arrsummary[i, j];
}
}
Console.WriteLine(s);
}


Jagged Arrays
A jagged array is an array whose elements are arrays. The elements of a jagged array can
be of different dimensions and sizes. A jagged array is sometimes called an "array-ofarrays."
//Decalaring a Jagged Array
int[][] myJaggedArray = new int[3][];
//Initialize the elements of the Jagged Array
myJaggedArray[0] = new int[5];
myJaggedArray[1] = new int[4];
myJaggedArray[2] = new int[2];
//Fill array elements with values.
myJaggedArray[0] = new int[] {1,3,5,7,9};
myJaggedArray[1] = new int[] {0,2,4,6};
myJaggedArray[2] = new int[] {11,22};
You can access individual array elements like these examples:
// Assign 33 to the second element of the first array:
myJaggedArray[0][1] = 33;
// get the value of second element of the third array:
int i = myJaggedArray[2][1];

Few Important methods in arrays.
GetUpperBound(), GetLowerBound() are the functions used to get the bound of a
array. These methods of the array class. You can use it with single dimension as well as
for multi-dimensional arrays.
GetLowerBound() is to get the upper limit of an array.
GetUpperBound is to get the lower limit of an array.
e.g.
string[] weeks = {"Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday", "Sunday"};
MessageBox.Show(weeks.GetUpperBound(0).ToString());
//the above statement returns 6 as the upper bound for the array weeks.
Syntax : arrayname.GetUpperBound/GetLowerBound(dimension)
Dimension refers to the which upper/lower bound should be found, 0 for first, 1 for
second and so on.
e.g.
string [,,] student_details = new string[10,20,15];
int upperlimit = 0;
// This will return 10 for the 1st row element
upperlimit = student_details.GetUpperBound(0);
MessageBox.Show(upperlimit.ToString());
// This will return 20 for the 2nd row of element
upperlimit = student_details.GetUpperBound(1);
MessageBox.Show(upperlimit.ToString());
For all GetLowerBound(dimension) it will return 0 as the base lower bound is zero in
.NET
.NET framework offers a myriad of languages which puts us programmers into a deep
thought process about which programming language best suits our needs.
Which language is the "best" language choice? If you are a VB wizard, should you take
the time to learn C# or continue to use VB.NET? Are C# ASP.NET pages "faster" than
VB.NET ASP.NET pages? These are questions that you may find yourself asking,
especially when you're just starting to delve into .NET. Fortunately the answer is simple:
there is no "best" language. All .NET languages use, at their root, functionality from the
set of classes provided by the .NET Framework. Therefore, everything you can do in
VB.NET you can do in C#, and vice-a-versa.
The differences occur in three main areas: syntax, object-oriented principles, and the
Visual Studio .NET IDE. Syntax concerns the statements and language elements. Object
Oriented differences are less obvious, and concern differences in implementation and
feature sets between the two languages. IDE differences include things like compiler
settings or attributes. There is also a fourth area of difference: language features that are
present in one language but have no equivalent in the other.
If you are more familiar with Java, JScript, or C/C++, you may find C#'s syntax more
familiar than VB.NET's.
If you've been doing VB for the past five years, there's no reason to think you have to
now switch to a new language (although you should always look to be learning new
things).
The fact is that VB.NET has all the facilities of VB such as not being case-sensitive,
having the option of using IntelliSense etc in addition to which you have an ocean of new
ideas & concepts thrown in for the benefit of programmers.
VB has matured as a language and if you do not know it already, its almost 11 years since
VB was born. It now provides all facilities for distributed computing and Internet
programming for which it was not useful earlier. With VB.NET, due to the .NET
framework all the classes and all the namespaces available with the other languages are
made available to VB also. This is in addition to the drag and drop facility of building
forms and web pages which was always the attraction in the use of VB. Thus it has the
dual advantage of ease of use and the availability of advanced features.
As already stated earlier both VB.NET and C# are equally powerful. So the primary
reason for which VB could not reach the zenith of popularity has been eradicated and
programmers who have been waiting for OOPs concepts to be incorporated into VB are
rewarded with this offering of Microsoft.
Private Sub PopulateRootLevel()
        treeClient.Nodes.Clear()
        Dim stBuild As New StringBuilder()
        stBuild.Append("select CLIENT_ID,CLIENT_NAME,o_or_p,active_yn,(select count(*) FROM client ")
        stBuild.Append(" WHERE reports_to_id=sc.CLIENT_ID) childnodecount FROM client sc where reports_to_id=0")
        selectQry = stBuild.ToString()
        'selectQry = "select CLIENT_ID,CLIENT_NAME,o_or_p,active_yn,(select count(*) FROM client " &
        '            " WHERE reports_to_id=sc.CLIENT_ID) childnodecount FROM client sc where reports_to_id=0"
        'Dim cmm As SqlCommand = New SqlCommand(selectQry)
        'Dim result As Object
        Dim dtTree = New DataTable
        dtTree = DataConnect.GetInstance.GetDt(selectQry)
        Dim dtTreeLang As New DataTable
        'If hdnLang.Value.ToString() <> "en" Then
        '    dtTreeLang = lt.changeLanguage(dtTree, hdnLang.Value.ToString())
        'Else
        dtTreeLang = dtTree
        'End If
        PopulateNodes(dtTreeLang, treeClient.Nodes)
    End Sub
    Private Sub PopulateNodes(ByVal dt As DataTable, ByVal nodes As TreeNodeCollection)
        For Each dr As DataRow In dt.Rows
            Dim tn As New TreeNode()
            tn.Text = dr("client_name").ToString() ' + "<asp:ImageButton runat='server' ImageUrl='~/Images/plus.gif' onClick='clickPlus()'>"
            tn.Value = dr("client_id").ToString()
            If dr("o_or_p").ToString().Trim() = "p" Then
                'If dr("active_yn").ToString().Trim() = "y" Then
                Dim strb = New StringBuilder()
                strb.Append("<u><img src='Images/1x1.gif'/><img src='Images/1x1.gif'/><img src='Images/1x1.gif'/>")
                strb.Append(tn.Text)
                strb.Append("</u><img src='Images/1x1.gif'/><img src='Images/1x1.gif'/>")
                strb.Append("<img src='Images/1x1.gif'/><img src='Images/1x1.gif'/><img src='Images/BlueStar.png'/>")
                tn.Text = strb.ToString()
                'tn.Text = "<u><img src='Images/1x1.gif'/><img src='Images/1x1.gif'/><img src='Images/1x1.gif'/>" &

                '    tn.Text &
                '    "</u><img src='Images/1x1.gif'/><img src='Images/1x1.gif'/>" &
                '    "<img src='Images/1x1.gif'/><img src='Images/1x1.gif'/><img src='Images/BlueStar.png'/>"
                'Else
                '    tn.Text = "<u><img src='Images/1x1.gif'/><img src='Images/1x1.gif'/><img src='Images/1x1.gif'/>" +
                '        tn.Text +
                '        "</u>"
                'End If

            Else
                Dim style As String
                style = "<style type='text/css'>" +
                    ".onClass{color:Black;}" +
                    ".onClass:hover{color:Blue;text-decoration:underline;}" +
                    "</style>"
                tn.Text = style + "<span class='onClass'>" + tn.Text + "</span>"
            End If
            tn.Target = dr("client_name").ToString()
            nodes.Add(tn)

            'If node has child nodes, then enable on-demand populating
            tn.PopulateOnDemand = (CInt(dr("childnodecount")) > 0)
        Next
    End Sub

    Private Sub PopulateSubLevel(ByVal parentid As Integer, ByVal parentNode As TreeNode)
        If rdbActive.Checked = True Then
            Dim stBuild As New StringBuilder()
            stBuild.Append("select CLIENT_ID,CLIENT_NAME,o_or_p,active_yn,(select count(*) FROM client ")
            stBuild.Append(" WHERE reports_to_id=sc.CLIENT_ID) childnodecount FROM client sc where reports_to_id=@parentID and active_yn='y'")
            selectQry = stBuild.ToString()
            'selectQry = "select CLIENT_ID,CLIENT_NAME,o_or_p,active_yn,(select count(*) FROM client " &
            '               " WHERE reports_to_id=sc.CLIENT_ID) childnodecount FROM client sc where reports_to_id=@parentID and active_yn='y'"
        ElseIf rdbAll.Checked = True Then
            Dim stBuild As New StringBuilder()
            stBuild.Append("select CLIENT_ID,CLIENT_NAME,o_or_p,active_yn,(select count(*) FROM client ")
            stBuild.Append(" WHERE reports_to_id=sc.CLIENT_ID) childnodecount FROM client sc where reports_to_id=@parentID")
            selectQry = stBuild.ToString()
            'selectQry = "select CLIENT_ID,CLIENT_NAME,o_or_p,active_yn,(select count(*) FROM client " &
            '   " WHERE reports_to_id=sc.CLIENT_ID) childnodecount FROM client sc where reports_to_id=@parentID"
        End If
        Dim objCommand = New SqlCommand(selectQry)
        objCommand.Parameters.Add("@parentID", SqlDbType.Int).Value = parentid
        Dim dt = New DataTable
        dt = DataConnect.GetInstance.GetDt(objCommand)
        Dim dtChild As New DataTable
        'If hdnLang.Value.ToString() <> "en" Then
        '    dtChild = lt.changeLanguage(dt, hdnLang.Value.ToString())
        'Else
        dtChild = dt
        'End If
        PopulateNodes(dtChild, parentNode.ChildNodes)
    End Sub

    Private Sub treeClient_SelectedNodeChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles treeClient.SelectedNodeChanged
        Try

            'btnNewNodeCancel_Click(sender, e)
            'ViewState("nodetext") = treeClient.SelectedNode.Text
            pnlGlobalMessage1.Visible = False
            lblGlobalMessage1.Visible = False
            btnAddClient.Text = "Add New Client/Program"
            btnOk.Enabled = True
            btnCancel.Enabled = True
            treeClient.SelectedNodeStyle.BackColor = Drawing.Color.Wheat
            selectQry = "select * from client where client_id='" & treeClient.SelectedNode.Value & "'"
            dtTable = DataConnect.GetInstance.GetDt(selectQry)
            Dim dtLang As New DataTable
            'If hdnLang.Value.ToString() <> "en" Then
            '    dtLang = lt.changeLanguage(dtTable, hdnLang.Value.ToString())
            'Else
            dtLang = dtTable
            'End If
            ViewState("clientdetails") = dtLang
            For Each dr As DataRow In dtLang.Rows
                treelocations.Nodes.Clear()
                labelClientID.Text = dr("client_id").ToString()
                'PopulateLocRootLevelid(Int32.Parse(labelClientID.Text))
                lblO_or_P.Text = dr("o_or_p").ToString()
                lblreports_to_id.Text = dr("reports_to_id").ToString()
                lblCreationDate.Text = dr("creation_dt").ToString()
                lblcreationid.Text = dr("creation_id").ToString()
                Dim p As String = "p"
                Dim o As String = "o"
                'If hdnLang.Value.ToString() <> "en" Then
                '    p = lt.LangTranslate("p", hdnLang.Value)
                '    o = lt.LangTranslate("o", hdnLang.Value)
                'End If
                If dr("o_or_p").ToString().Trim() = p Then
                    pnlAddOrg.Enabled = False
                    pnlNewRootClient.Enabled = False
                    TabContainer1.Tabs(1).Enabled = True
                    Session("clientid") = labelClientID.Text
                    Dim reg As New Regex("<[^<>]+>")
                    'txtProgNm.Text = treeClient.SelectedNode.Text.Replace("", "")
                    txtProgNm.Text = reg.Replace(treeClient.SelectedNode.Text, "")
                    If treeClient.SelectedNode.Parent Is Nothing Then
                        lblpanelTitle.Text = txtProgNm.Text
                    Else
                        lblpanelTitle.Text = treeClient.SelectedNode.Parent.Target.ToString() + "&nbsp;/&nbsp;" + txtProgNm.Text
                    End If
                    lblLocAddStatus.Visible = False
                    lblpanelTitle.Font.Bold = True
                    lblSurgereid.Text = dr("surgere_id").ToString()
                    txtNotes.Text = dr("notes").ToString()
                    TabContainer1.ActiveTab = TabContainer1.Tabs(1)
                    If treeClient.SelectedNode.Parent Is Nothing Then
                        labelclientPath.Text = txtProgNm.Text
                        'lblFacLocTitle.Text = labelclientPath.Text
                    Else
                        labelclientPath.Text = treeClient.SelectedNode.Parent.Target.ToString() + "&nbsp;:&nbsp;" + txtProgNm.Text
                        'lblFacLocTitle.Text = labelclientPath.Text
                    End If
                    labelclientPath.Visible = True
                    msgpanel2.Visible = False
                    'chkAddClient.Enabled = False
                    btnAddClient.Enabled = False
                    If dr("active_yn").ToString().Trim() = "n" Then
                        btndisablepgm.Text = "Enable"
                    Else
                        btndisablepgm.Text = "Disable"
                    End If
                    'treeClient.SelectedNode.Selected = False
                    txtSurgereID.Text = ""
                    txtNodeNotes.Text = ""
                    txtNodeNm.Text = ""
                    TabContainer3.Tabs(1).Enabled = False

                    treelocations.DataSource = Nothing
                    treelocations.DataBind()

                    PopulateLocRootLevelid(Session("clientid"))
                    treelocations.ExpandAll()


                    ContactControls.UnLoadContactDetails()
                    ContactControls.LoadContactDetails()

                    Packaging1.UnloadControls()
                    Packaging1.getcontainerList()



                    POs1.unloadControl()
                    POs1.controlLoaded()



                    SupplierDetails.UnloadSuppliers()
                    SupplierDetails.LoadSupplier("")

                    Production1.controlUnloaded()
                    Production1.controlLoaded()


                    usrDunnage1.controlUnloaded()
                    usrDunnage1.controlLoaded()

                    customerControl1.conltrolLoaded()

                    '   PopulateLocRootLevelid(treeClient.SelectedNode.Value)
                    'Packaging1.UnloadControls()
                    'POs1.unloadControl()
                    'Production1.controlUnloaded()
                    'SupplierDetails.LoadSupplier()
                    'ContactControls.LoadContactDetails()
                    'Production1.controlLoaded()
                    'usrDunnage1.controlUnloaded()
                    'usrDunnage1.controlLoaded()
                    '  Packaging1.getcontainerList()
                    '  POs1.grdPoFill()
                    treeClient.SelectedNode.Selected = False
                    TabContainer2.ActiveTab = TabContainer2.Tabs(0)

                Else
                    'Dim reg As New Regex("<[^<>]+>")
                    'Dim reReg As New Regex("<[^<>]+<")
                    'txtNodeNm.Text = reReg.Replace(treeClient.SelectedNode.Text, "")
                    'txtNodeNm.Text = reg.Replace(txtNodeNm.Text, "")
                    txtNodeNm.Text = treeClient.SelectedNode.Target.ToString()
                    If treeClient.SelectedNode.Parent Is Nothing Then
                        lblpanelTitle.Text = txtNodeNm.Text
                    Else
                        lblpanelTitle.Text = treeClient.SelectedNode.Parent.Target.ToString() + "&nbsp;/&nbsp;" + txtNodeNm.Text
                    End If
                    'lblpanelTitle.Text = treeClient.SelectedNode.Target.ToString()
                    lblpanelTitle.Font.Bold = True
                    txtSurgereID.Text = dr("surgere_id").ToString()
                    txtNodeNotes.Text = dr("notes").ToString()
                    txtSurgereID.Enabled = True
                    btnDel.Text = "Delete"
                    btnDel.Enabled = True
                    btnAddClient.Enabled = True
                    'chkAddClient.Visible = True
                    pnlAddOrg.Visible = True
                    'chkAddClient.Enabled = True
                    If treeClient.SelectedNode.ChildNodes.Count <> 0 Then
                        btnDel.Enabled = False
                    End If
                    pnlAddOrg.Enabled = True
                    pnlNewRootClient.Enabled = True
                    Session.Remove("clientid")
                    TabContainer1.Tabs(1).Enabled = False
                    Dim dtclient As New DataTable
                    dtclient = DataConnect.GetInstance.GetDt("select * from checkclientid('" & treeClient.SelectedNode.Value & "')")
                    If dtclient.Rows.Count <> 0 Then
                        btnDel.Enabled = False
                    Else
                        btnDel.Enabled = True
                    End If
                End If
            Next

            '
            ' TODO --Security
            '________________________________________________________________________________________________________________________
            ''User security-Bigin
            ''________________________________________________________________________________________________________________________
            'Dim dtUser As DataTable = Session("user_session")
            'Dim user_security As String = dtUser.Rows(0)("user_security").ToString()
            'If user_security = "Basic User" Or user_security = "SPARCS" Then
            '    btnDel.Enabled = False
            '    btnAddClient.Enabled = False
            '    btnOk.Enabled = False
            '    btnupdatepgm.Enabled = False
            '    btndisablepgm.Enabled = False
            '    btnNewLocation.Enabled = False
            '    btnUpdate.Enabled = False
            '    cmdSave.Enabled = False
            '    cmdDel.Enabled = False
            'End If
            ''________________________________________________________________________________________________________________________
            ''User security-End
            ''________________________________________________________________________________________________________________________

            optOrg1.Enabled = False
            optOrg2.Enabled = False
            'chkAddClient.Checked = False

        Catch ex As Exception
            pnlGlobalMessage.Visible = True
            lblGlobalMessage.Text = "A technical issue has occurred.  A message has been sent to the development team.  Sorry for the inconvenience."
            If hdnLang.Value.ToString() <> "en" Then
                lblGlobalMessage.Text = lt.LangTranslate(lblGlobalMessage.Text, hdnLang.Value)
            End If
            lblGlobalMessage.Visible = True
            dt = Session("user_session")
            Worker.HandleError(ex, "Client/ProgramList", Int64.Parse(dt.Rows(0)("user_id")), Request.Browser.Browser.ToString())
        End Try

    End Sub

    Private Sub treeClient_TreeNodePopulate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.TreeNodeEventArgs) Handles treeClient.TreeNodePopulate
        PopulateSubLevel(CInt(e.Node.Value), e.Node)
    End Sub
Constants &Variables
A variable is a named memory location. They are programming elements that can change
during program execution. Data that needs to be stored in memory & accessed at a later
time are stored in variables. Instead of referring to the memory location by the actual
memory address you refer to it with a variable name.

Variables are declared as follows
Dim a as Integer
They can also be initialized at the time of declaration as follows:
Dim a as Integer = 10

Constants are very similar to variables. The main difference is that the value contained in
memory cannot be changed once the constant is declared. When you declare a constant
its value is also specified and this value cannot be changed during program execution.
Constants are used in situations where we need to keep the value in some memory
location constant. If you use hard-coded values, and the value is changed then it has to be
changed in all the locations in the code where it has been used. Instead if we are using
constants, all we will need to do is to change the value of the constant. This would
propagate the changes to our entire application.

Constants are declared as follows
Const x as Integer

VB.NET supports block-level scoping of variables. That is you can declare and use
variables as and when you need them. Thus, if a variable is required within a ‘for’ block
it can be declared within the block and its scope will be the end of the block.

Simple Types (Primitive Data types)
Simple or value type variables are those, which are assigned space in the stack instead of
the heap. All the primitive types such as int, double etc are value type variables. The
simple types basically consist of Boolean and Numeric types, where Numeric is further
divided into Integral and Floating Point.
The first rule of value types is that they cannot be null. Anytime you declare a variable of
value type, you have allocated the number of bytes associated with that type on the stack
and are working directly with that allocated array of bits. In addition, when you pass a
variable of value type, you are passing that variable’s value and not a reference to the
underlying object.

Object Type
Object type or reference type variables are those, which are allocated storage space in the
heap. Reference type objects can be null. When a reference type is allocated under the
covers a value is allocated on the heap and a reference to that value is returned. There are
basically four reference types: classes, interfaces, delegates and arrays.

Class Type
Custom data types are available in .NET framework in the form of classes or class type. It
is nothing but a set of data and related behavior that is defined by the developer.
Object type and class type are both reference type variables. The only difference comes
from the fact that object type consists of objects predefined and available with the .NET
framework such as string whereas class type consists of custom user defined data types
such as the Class Employee given below.

Class Employee
Dim empid As Integer
Dim empname As String
Public Sub New()
empid = 10
empname = "Reshmi"
End Sub
End Class
Overloading provides the ability to create multiple methods or properties with the same
name, but with different parameters lists. This is a feature of polymorphism. It is
accomplished by using the Overloads keyword in VB.NET. A simple example would be
an addition function, which will add the numbers if two integer parameters are passed to
it and concatenate the strings if two strings are passed to it.


Class test
Public Overloads Function Add(ByVal x As Integer, ByVal y As
Integer)
Return x + y
End Function
Public Overloads Function Add(ByVal x As String, ByVal y As
String)
Return x & y
End Function
Shared Sub main()
Dim a As new test
Dim b As Integer
Dim c As String
b = a.Add(1, 2)
c = a.Add("Reshmi", " Nair")
System.Console.Writeline(b)
System.Console.Writeline(c)
End Sub
End Class
O/P:
3
Reshmi Nair



Overriding
Class inheritance causes the methods and properties present in the base class also to be
derived into the derived class. There might arise a situation wherein you would like to
change the functionality of an inherited method or property. In such cases we can
override the method or property of the base class. This is another feature of
polymorphism. You can accomplish this in VB.NET by using the Overridable keyword
with the base class method and the Overrides keyword with the derived class method.
Public Class shapes
Public Overridable Sub display()
Console.WriteLine("Shapes")
End Sub
End Class
Public Class square
Inherits shapes
Public Overrides Sub display()
Console.WriteLine("This is a square")
End Sub
End Class
Public Class rectangle
Inherits shapes
Public Overrides Sub display()
Console.WriteLine("This is a rectangle")
End Sub
End Class
The above example is just an indication to how overriding can be implemented in either
VB.NET.
This summary is not available. Please click here to view the post.
Properties are named members of classes, structs, and interfaces. They provide a flexible
mechanism to read, write, or compute the values of private fields through accessors.
Properties are an extension of fields and are accessed using the same syntax. Unlike
fields, properties do not designate storage locations. Instead, properties have accessors
that read, write, or compute their values.

Get accessor
The execution of the get accessor is equivalent to reading the value of the field.
The following is a get accessor that returns the value of a private field name:
Dim name as String ’ the name field
Property Name() As String ’ the name property
Get
Return name
End Get
End Property

Set accessor

The set accessor is similar to a method that returns void. It uses an implicit parameter
called value, whose type is the type of the property. In the following example, a set
accessor is added to the Name property:
Dim name as String ’ the name field
Property Name() As String ’ the name property
Get
Return name

End Get
Set(ByVal Value As String)
Name = value
End Set
End Property
When you assign a value to the property, the set accessor is invoked with an argument
that provides the new value. For example:
e1.Name = "Reshmi" // The set accessor is invoked here
It is an error to use the implicit parameter name (value) for a local variable declaration in
a set accessor.
How to make a Property Read Only/Write Only
There are times when we may want a property to be read-only – such that it can’t be
changed. This is where read-only properties come into the picture. A Read Only property
is one which includes only the get accessor, no set accessor.

For instance,
Public ReadOnly Property EmpID() as Integer
Get
Return empid
End Get
End Property
Similar to read-only properties there are also situations where we would need something
known as write-only properties. In this case the value can be changed but not retrieved.
To create a write-only property, use the WriteOnly keyword and only implement the set
block in the code as shown in the example below.
Public WriteOnly Property e as string
Set
e = Value
End Set
End Property
A structure allows you to create your own custom data types and it contains one or more
members that can be of different data types. It can contain fields, methods, Etc.,
Structures are very similar to classes but there are some restrictions present in the case of
structures that are absent in the case of classes. For example you cannot initialize
structure members. Also you cannot inherit a structure whereas classes can be inherited.
Another important feature of structures differentiating it from classes is that a structure
can't have a default parameter-less constructor or a destructor. A structure is created on
the stack and dies when you reach the closing brace in C# or the End structure in
VB.NET.
But one of the most important differences between structures and classes is that structures
are referenced by value and classes by reference. As a value type, allocated on the stack,
structs provide a significant opportunity to increase program efficiency. Objects on the
stack are faster to allocate and de-allocate. A struct is a good choice for data-bound
objects, which don’t require too much memory. The memory requirements should be
considered based on the fact that the size of memory available on the stack is limited than
the memory available on the heap.
Thus we must use classes in situations where large objects with lots of logic are required.
Struct – Code: Sample code showing the Class vs. Structures
Imports System
Class Test
Dim classvar As Integer
Dim anothervar As Integer = 20
Sub New()
classvar = 28
End Sub
Structure ExampleStruct
Dim i As Integer
Sub New(ByVal j As Integer)
i = j
End Sub
Sub trialMethod()
Console.WriteLine("Inside Trial Method")
End Sub
End Structure
Shared Sub main()
Dim t As New Test()
Dim strct As New ExampleStruct(20)
Console.WriteLine(strct.i)
strct.i = 10
Console.WriteLine(t.classvar)
Console.WriteLine(strct.i)
strct.trialMethod()
End Sub
End Class
O/P: -
28
20
10
Inside Trial Method
In the above example, I have declared and used a constructor with a single parameter for
a structure. Instead if I had tried to use a default parameter-less parameter I would have
got an error. But the same is possible in the case of classes as shown by the default
parameter-less constructor, which initializes the classvar variable to 28.
Another point to note is that a variable called anothervar has been declared and initialized
within the class whereas the same cannot be done for members of a structure.