net notes
net notes
Net programming
UNIT-I
.Net Framework:
The .net framework is a new computing platform that simplifies applications development in the highly
distributed environment of the Internet.
.Net framework is a new easy & extensive programming platform.
.Net is a framework, it’s not a programming language. But it supports more than 50 languages.
.Net is a operating system & platform independent.
Windows/Intel Combination(WinTel):
The Microsoft .Net framework is an integrative and manage environment for the development &
execution of the coding
The .Net infrastructure consists of all the technologies that help in creating and running robust,
scalable and distributed applications.
The .Net framework exists as a “Layer between .Net applications and Operating System”.
The .Net framework consists of
1. Web Forms
2. Windows Forms
3. Console Applications
Web forms are used in web based applications where as Windows forms are used in the windows
based applications for providing an interactive user interface.
Console applications that can be executed from the command line.
V
Common Language Specification(CLS) I
S
U
A
Windows Forms L
Web forms Web Services (User Interface)
ASP .Net S
T
ADO.Net & XML U
D
I
O
Base Class Library
.
N
Common Language Runtime (CLR) E
T
Operating System
CCCk;fjl
CLR Application
System.io.file
Programming Language
Execution Platform……
Windows
File Packet Linux
System PC System File System
ASP.NET
Unmanaged Code
VBRUN CLR
OS
Infrastructure of CLR
The CLR provides the functionalities such as Exception handling, debugging and vesioning supports
to any .Net languages.
The CLR provides the number of sevices the includes,
Loading & execution of programs.
Memory isolation for applications
Verification of Type safety
Compilation of IL into native executable code
Providing metadata
Memory management(Automatic garbage collection)
Security
Managing Errors and Exception.
Components of CLR
The premier language for the CLR are VB, C# and c++ with managed extension.
The code that is developed with a language compiler that targets the CLR is called managed
code.
The code that is developed without considering the conventions and requirements of CLR is
called Unmanaged code.
Unmanaged code executes in limited debugging and without garbage collection
process(manages the allocation and de allocation of memory for an application).
Common Type System:
Namespace:
This namespace helps to create the logical group of related Classes and Interfaces that can be
used by any language targeted by .Net Framework.
Namespace allow you to organize the classes so that they can easily access in other applications.
Ex: System.console
(Namespace) . (Class)
Assemblies:
An assembly is a deployable unit that contains all the information about the implementation of
classes and structures & Interfaces.
In .net coding reusability is achieved through assemblies.
Any coding in .net must be stored in assemblies on its compilation time.
In addition to MSIL (MicroSoft Intermediate Language) code an assembly also contains 4
sections…..
1. Assembly metadata (manifest assembly)
2. Type metadata (data type information)
3. Program Code (coding in MSIL format)
4. Resources (files used in the programs)
Assemblies are of 2 types………..
1. Private: It is used only in one particular application.
2. Public: It is used in different applications.
Arrays
Classes
Value type hold data within its own memory location and own copy of data for operation.
Reference type means the variable contain a pointer to a memory location that holds data. CLR-
Architecture of CLR :-
Class loader
Class loader:-
Which loads the classes into CLR at the runtime?
Code manager:-
Managing the code during execution.
Garbage collector:-
If supports the memory management and also supports unused memory at the
runtime.
Type check up:-
Checks for type safety at runtime
Debug Engine :-
If supports debugging at runtime and also allow the developer to debug different
types of application.
Exception Manager:-
Handles the exception at runtime.
Security Engine:-
If enforces the security rules at runtime.
Thread support:-
It provides multithreading support to application.
COM Marshaler:-
It supports marshalling of data between COM object
Exe Code
Class Loader
JIT Compiler
Source Code
Compiler
Exe Code
Verify Test
JIT Compiler
Runtime Manager
Output
Managed code:
The CLR is responsible for managing the execution of code compiled for .net platform.
The code statisfied the CLR at runtime in order to execute. This is referred to as managed
code.
In the process of compiling and executing the managing code as follows,
i. When you compile a program develop in a language that targets the CLR instanced
of compiling the source code to machine code, the compiler translate source code to
MSIL code.
ii. In addition to translating the code into MSIL compiler also produce metadata, about
the program.
iii. Metadata contains the description of programs. Such as classes and interface used in
the program.
iv. In intermediate language and metadata and linked in an assembly via links.
v. The compiler creates the .exe (or) .dll file.
vi. When execute the .exe file the code from the base class library and send to the class
loader. The class loader loads the code into the memory.
vii. During JIT compilation the code is also checked for type safety.
viii. During the process of compilation the JIT compiler compiles only the code that is
require during the execution, instance of compiling the intermediate language code.
When an uncompelled method is invoked during the execution, the JIT compiler
converts the IL for that method into native code. This process same time in memory
to convert the IL into native code.
ix. After converting the IL into native code the converted code is send it to the .net
runtime manager.
x. The runtime manager executes the code and produces the output.
You don't actually need the Visual Studio .NET product to write applications in the Visual
Studio .NET language.
The actual ability to run Visual Studio .NET code is included with the .NET Framework.
You could actually just write all of your Visual Studio .NET using a text editor such as
Notepad.
However, by far the easiest way to write in Visual Studio .NET is by using the Visual
Studio.NET Integrated Development Environment, also known as the IDE.
This is what you actually see when working with Visual Studio .NET – the windows, boxes,
etc. The IDE provides a wealth of features that are unavailable in ordinary text editors – such
as code checking, visual representations of the finished application, and an explorer that
displays all of the files that make up your project.
Toolbox
The Toolbox contains reusable components that can be inserted into your application. These can
range from buttons to data connectors to customized controls either purchased or developed
yourself.
Design Window
The Design window is where a lot of the action takes place. This is where you will draw your user
interface and write your code. This window is sometimes referred to as the Designer.
Solution Explorer
The Solution Explorer window contains a hierarchical view of your solution. A solution can contain
many projects while a project contains code and code references that solve a particular problem.
Class View
The Class View window (shown as a tab with the Solution Explorer) gives you a tree view of the
classes in your program and shows the properties and methods that each contains. A class is code
file that groups data and the functions that manipulate it together into one unit. A property is data,
and a method is a function or subroutine.
Properties
The Properties window shows what properties the selected object makes available. Although you
can set these properties in your code, sometimes it is much easier to set them while you are
designing your application. You will notice that the File Name property has the value Form1.vb.
This is the physical file name for the form's code and layout information.
Task List
The Task List window highlights any errors encountered when you try to run your code. Clicking on
the item in this window will take you to the line of code containing the error.
Output
When you run your code the progress made in reading it (or compiling it) is registered via messages
posted in the Output window.
Dynamic Help
The Dynamic Help window displays a list of help topics that relate to whatever in the IDE has focus.
If you click on the form in the Design Window and then open Dynamic Help, you will see a list of
help topics relating to forms.
The Toolbox:
The Toolbox is accessed via the View | Toolbox menu option, the Toolbox icon on the
Standard menu bar, or by pressing Ctrl + Alt + X.
The Toolbox contains a tabbed view of the various controls and components that can be
placed onto your form.
Controls such as textboxes, buttons, radio buttons, and drop-down boxes can be selected and
then drawn onto your form. For the HelloUser application, we will only be using the controls
on the Windows Forms tab:
Here we can see a listing of standard .NET controls for Windows forms. The down arrow
button to the right of the Clipboard Ring tab title actually scrolls the Windows Forms control
list down as there are too many to fit in otherwise.
The up arrow button on the Windows Forms tab scrolls the list up. Note that the order in
which your controls appear may be different.
Controls can be added to your forms in any order, so it does not matter if we add the label
control after the textbox or the buttons before the label.
Control Prefix
Button btn
ComboBox cbo
CheckBox chk
Label lbl
ListBox lst
MainMenu mnu
RadioButton rdb
PictureBox pic
TextBox txt
Hungarian Notation can be a real time-saver when looking at code someone else wrote, or at
code that you have written months past. However, by far the most important thing is to be
consistent in your naming.
When you start coding, pick a convention for your naming. It is recommended that you use the
de facto standard Modified-Hungarian for Visual Basic .NET, but it is not required.
Once you pick a convention, stick to it. When modifying someone else's code, use theirs. There
is very little code that is ever written, put into production and then forgotten.
A standard naming convention followed throughout a project will save countless hours when
the application is maintained.
Due to the typographic constraints in publishing, it is not possible to put the Sub declaration
on one line. Visual Basic .NET allows you to break up lines of code by using the underscore
character (_) to signify a line continuation. The space before the underscore is required. Any
whitespace preceding the code on the following line is ignored.
Sub is an example of a keyword. In programming terms, a keyword is a special word that is used to
tell Visual Basic .NET to do something special. In this case, it tells Visual Basic .NET that this is a
procedure. Anything that we type between the lines Private Sub and End Sub will make up the event
procedure for the OK button.
3. After you have added the code, go back to the Design tab, and double-click on the Exit button.
Add the highlighted code to the ExitButton_Click event procedure.
4. Now that the code is finished, the moment of truth has arrived and we can see our creation. First
though, save your work by using File | Save from the menu, or by clicking the disk icon on the
toolbar.
5. Now click on the Start button on the toolbar. You will notice a lot of activity in the Output
window at the bottom of your screen. Providing you haven't made any mistakes in entering the code,
this information just lets you know what files are being loaded to run your application.
It's at this point that Visual Studio .NET will compile the code. Compiling is the activity of taking
the Visual Basic .NET source code that you've written and translating it into a form that the
computer understands. After the compilation is complete, Visual Studio .NET will run (also known
as execute) the program and we'll be able to see the results.
6. When the application loads you will see the main form. Enter a name and click on OK (or press
the Alt+O key combination):
7. A window known as a message box appears, welcoming the person whose name was entered in
the textbox to Visual Basic .NET – in this case Deborah:
8. After you close the message box by clicking on its OK button, click on the Exit button on our
form. The application will close and you will be brought back to the Visual Basic .NET IDE.
The other help commands in the Help menu (Contents, Index, and Search), function just as they
would in any other Windows application.
The domain of help topics to search and display is defined by the profile that we defined at
installation. However, the Edit Filters… menu option allow you to further focus what types of
documentation to include in the search.
VISUAL BASIC . NET
Toolbox
The Toolbox is a palette of developer objects, or controls, that are placed on forms or web
pages, and then code is added to allow the user to interact with them. An example would be
TextBox, Button and ListBox controls. With these three controls added to a Windows Form object
the developer could write code that would take text, input by the application user, and added to the
ListBox after the button was clicked.
Solution Explorer
This is a section that is used to view and modify the contents of the project. A Visual Studio
Windows Application Project will generally have a Form object with a code page, references to
System components and possibly other modules with special code that is used by the application.
Properties Windows
The properties windows shows all the control (like textbox) properties to be change at design
time. Most of these properties can be change at run time with some code, but basically most of this
properties change the way the control is display on your application.
Code / Design view
This is where the magic takes place. Forms are designed graphically. In other words, the
developer has a form on the screen that can be sized and modified to look the way it will be
displayed to the application users.
Important Features:-
1. One IDE for all .NET Projects
Visual Studio .NET IDE provides a single environment for developing all types of
.NET applications. Application’s range from single windows applications to complex n-tier
applications and rich web applications.
2. Option to choose from Multiple Programming Languages
You can choose the programming language of your choice to develop applications
based on your expertise in that language. You can also incorporate multiple programming
languages in one .NET solution and edit that with the IDE.
3. IDE is Customizable
You can customize the IDE based on your preferences. The My Profile settings
allow you to do this. With these settings you can set the IDE screen the way you want, the
way the keyboard behaves and you can also filter the help files based on the language of
your choice.
4. Built-in Browser
The IDE comes with a built-in browser that helps you browse the Internet without
launching another application. You can look for additional resources, online help files,
source codes and much more with this built-in browser feature.
When we open VS .NET from Start->Programs->Microsoft Visual Studio .NET-
Microsoft Visual Studio .NET the window that is displayed first is the Start Page which is
shown below. The start Page allows us to select from the most recent projects (last four
projects) with which we worked or it can be customized based on your preferences.
This center window of the IDE is also where developers write the code that makes
everything in the application work. The code is written in modules, or files, that are either
connected to an object (Forms) or called specifically when needed.
The Integrated Development Environment (IDE) shown in the image below is what we actually
work with. This IDE is shared by all programming languages in Visual Studio. You can view the
toolbars towards the left side of the image along with the Solution Explorer window towards the
right.
Following are different templates under Project Types and their use.
1. Windows Application: This template allows creating standard windows based applications.
2. Class Library: Class libraries are those that provide functionality similar to Active X and
DLL by creating classes that access other applications.
3. Windows Control Library: This allows creating our own windows controls. Also called as
User Controls, where you group some controls, add it to the toolbox and make it available to
other projects.
4. ASP .NET Web Application: This allows creating web-based applications using IIS. We
can create web pages, rich web applications and web services.
5. ASP .NET Web Service: Allows creating XML Web Services.
6. Web Control Library: Allows creating User-defined controls for the Web. Similar to user
defined windows controls but these are used for Web.
7. Console Application: A new kind of application in Visual Studio .NET. They are command
line based applications.
8. Windows Service: These run continuously regardless of the user interaction. They are
designed for special purpose and once written, will keep running and come to an end only
when the system is shut down.
9. Other: This template is to develop other kinds of applications like enterprise applications,
database applications etc.
The Menu:
Visual Studio .NET's menu is dynamic, meaning that items will be added or removed depending on what you
are trying to do. While we are still looking at the Get Started page, the menu bar will only consist of the File,
Edit, View, Tools, Window, and Help menus.
File
It seems every Windows program has a File menu. It has become the standard where you
should find, if nothing else, a way to exit the application. In this case, you can also find ways of opening and
closing single files and whole projects.
Edit
The Edit menu provides access to the items you would expect: Undo, Redo, Cut, Copy, Paste, and Delete.
View
The View menu provides quick access to the windows that make up the IDE, such as the Solution Explorer,
Properties window, Output window, Toolbox, etc.
Project
The Project menu allows you to add various extra files to your application.
Build
The Build menu becomes important when you have completed your application and want to be able to run it
without the use of the Visual Basic .NET environment
Debug
The Debug menu allows you to start and stop running your application within the Visual Basic .NET IDE. It
also gives you access to the Visual Studio .NET debugger. The debugger allows you to step through your
code while it is running to see how it is behaving.
Data
The Data menu helps you use information that comes from a database. It only appears when you are working
with the visual part of your application (the [Design] tab will be the active one in the main window), not
when you are writing code. Chapters 15 and 16 will introduce you to working with databases.
Format
The Format menu also only appears when you are working with the visual part of your application. Items on
the Format menu allow you to manipulate how the windows you create will appear to the users of your
application.
Tools
The Tools menu has commands to configure the Visual Studio .NET IDE, as well as links to other external
tools that may have been installed.
Window
The Window menu has become standard for any application that allows more than one window to be open at
a time, such as Word or Excel. The commands on this menu allow you to change the physical layout of the
windows in the IDE.
Help
The Help menu provides access to the Visual Studio .NET documentation. There are many different ways to
access this information (for example, via the help contents, an index, or a search). The Help menu also has
options that connect to the Microsoft Web site to obtain updates or report problems.
R
The Toolbars:
There are many toolbars available within the IDE, including Formatting, Image Editor, and Text
Editor, which you can add to and remove from the IDE via the View | Toolbars menu option.
Each one provides quick access to often-used commands, preventing you from having to navigate
through a series of menu options.
For example, the leftmost icon on the toolbar shown below (New Project) is available from the
menu by navigating to File | New | Project.
The default toolbar (called Standard) appears at the top of the IDE as:
Tool Bars
The toolbar is segmented into groups of related options, which are separated by a vertical bar.The
first five icons provide access to the commonly used project and file manipulation options
available through the File and Project menus, such as opening and saving files.
The next group of icons is for editing (Cut, Copy, and Paste).The third group of icons is for editing
and navigation. The navigation buttons replicate functionality found in the View menu and allow
us to cycle through the tabs at the top of the main window.
The fourth group of icons provides the ability to start your application running (via the blue
triangle) and to specify build configurations.
There are times when you want certain parts of your code only to appear in a debug version, a bit
like a rough draft version of your application.
For example, you may have code in your application that is only useful for tracking down problems
in the application.
When it is time to release your application to the world, you will want to exclude this code by
setting the Solution Configurations settings to Release. You can also access the functionality
offered by this group via the Build and Debug menus.
The next section allows you to locate parts of your code quickly. The simplest way to search is to
type some text into the Find textbox and hit Enter. If the text is found, it will be highlighted in the
central window.
The Find in Files option allows you to specify more sophisticated searches, including matching the
case of the text, looking in specific files or projects, and replacing the found text with new text.
The search functionality can also be accessed via the Edit | Find and Replace menu option.
The next group of icons provides quick links back to the Solution Explorer, Properties window,
Toolbox, and Class View. If any of these windows are closed, clicking the appropriate icon will
bring it back into view.
Toolbox Window
The toolbox window is the window that gives us access to all controls, components, etc. As you can
see from the image below, the toolbox uses tabs to divide it's contents into categories (Data,
Components, Windows Forms and General).
The Data tab displays tools for creating datasets and making data connections, the Windows Forms
tab displays tools for adding controls to forms, the General tab is left empty by default, the
Clipboard Ring tab displays recent items stored in the clipboard and allows us to select from them.
Solution Explorer Window
The Solution Explorer window gives an overview of the solution we are working with and lists
all the files in the project. An image of the Solution Explorer window is shown below
The Server Explorer window is a great tool that provides "drag and drop" feature and helps
us work with databases in an easy graphical environment. For example, if we drag and drop a
database table onto a form, VB .NET automatically creates connection and command objects that
are needed to access that table. The image below displays Server Explorer window.
Intellisense
Intelligence is what that is responsible for the boxes that open as we type the code.
IntelliSense provides a list of options that make language references easily accessible and helps us to
find the information we need. They also complete the typing for us. The image below displays that.
The properties window allows us to set properties for various objects at design time. For
example, if you want to change the font, font size, back color, name, text that appears on a button,
textbox etc, you can do that in this window. Below is the image of properties window. You can view
the properties window by selecting View->Properties Window from the main menu or by
pressing F4 on the keyboard.
Output Window
The output window as you can see in the image below displays the results of building and
running applications.
Variables:
Variables in VB.net 2008 are used to store values and also they have a datatype and a unique name.
Naming Convention:
Variables in Visual Basic should start with an alphabet or a letter and should not contain any special
characters like %,&,!,#,@ or $. The variable should not exceed 255 characters.
Scope of Variables: A variable declared in the general declaration of a form can be used in all the
procedures. Variables declared inside a procedure will have a scope only inside the procedure, so
they are declared using the Dim keyword.
All variables have:
Data type – kind of data the variable can contain
Value – Every variable refers to a memory location that contains data. This value can be
specified by the programmer.
• Boolean, Char
To declare a VB .NET variable, write:
o Keyword “Dim”
o Keyword “As”
o Data type
• Example:
‘declare a variable
Dim i As Integer
• A value can be assigned by the programmer to a variable
• Assignment operator (=) assigns the value on the right to the variable named on the left side
• Example:
' populate the variable
i=1
• The code for both declare and initialize a variable can be written in one statement:
' declare a variable
Dim i As Integer = 1
• Several variables of the same data type can be
declared in one statement:
Dim x, y, z As Integer
Example
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim c As Integer
c = Val(TextBox1.Text) + Val(TextBox2.Text)
TextBox3.Text = c
End Sub
End Class
Description:
In the above example, Dim statement is used to declare variables, c that can be used within the sub
procedure.
Data Types
Data Type in Visual Basic.net 2008 defines the type of data a programming element should be
assigned, how it should be stored and the number of bytes occupied by it.
Integer
String
Single
Double
Boolean
char.
Boolean 2
Byte 1
Char 2
Date 8
Decimal 16
Single 4
Double 8
Short 2
Integer 4
Long 8
String Variable
Boolean
Boolean is really a flag and not a numeric data type. The storage size is 16 bits in VB6 and
varies by platform in .NET.
Integer and Long have the same name and type character in VB6/VBA and VB.NET, but
they are different data types altogether. To stay clear one can use Int16, Int32 and Int64 in
.NET.
Currency
LongLong
Introduced with Office 2010, LongLong is a 64-bit signed integer that is available in VBA7
running on a 64-bit platform. It is unsupported in VB6, VBA6 and on 32-bit platforms.
Decimal
Decimal is a signed 96-bit integer, which is divided by a scaling factor. The scaling factor
varies from 1 to 1E+28. A Decimal can represent 29 decimal digits: integers and decimal
numbers with max 28 decimal places. The binary representation consists of a 1-bit sign, a
96-bit integer number and the scaling factor. VB6 supports Decimal with the Variant data
type. You cannot declare a variable to be of type Decimal. You can, however, create a
Variant whose subtype is Decimal using the CDec function.
Single
Double
Constants in VB.NET
Constants in VB.NET is declared using the keyword Const. Once declared, the value of these
constants cannot be altered at run time.
Syntax:
In the above syntax, the Public or Private can be used according to the scope of usage. The Value
specifies the unchangable value for the constant specifed using the name constName.
Example:
Public Class Form1
Public Const PI As Double = 3.14159
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim r, a As Single
r = Val(TextBox1.Text)
a = PI * r * r
TextBox2.Text = a
End Sub
End Class
Description:
In the above example, a constant PI is declared as Public so that it can be used anywhere in the
class.
Array:
Arrays in VB.net are declared using the Dim statement, but by using the access specifiers Public,
Private, Static, Protected the scope of usage of arrays can be controlled within the code.
To declare an array in VB.Net, you use the Dim statement. For example,
The elements in an array can be stored and accessed by using the index of the array. The following
program demonstrates this:
Module arrayApl
Sub Main()
Dim n(10) As Integer ' n is an array of 11 integers '
Dim i, j As Integer
' initialize elements of array n '
For i = 0 To 10
n(i) = i + 100 ' set element at location i to i + 100
Next i
' output each array element's value '
For j = 0 To 10
Console.WriteLine("Element({0}) = {1}", j, n(j))
Next j
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
Element(0) = 100
Element(1) = 101
Element(2) = 102
Element(3) = 103
Element(4) = 104
Element(5) = 105
Element(6) = 106
Element(7) = 107
Element(8) = 108
Element(9) = 109
Element(10) = 110
Multi-Dimensional Arrays
VB.Net allows multidimensional arrays. Multidimensional arrays are also called rectangular arrays.
Module arrayApl
Sub Main()
Dim a(,) As Integer = {{0, 0}, {1, 2}, {2, 4}, {3, 6},{4, 8}}
Dim i, j As Integer
' output each array element's value '
For i = 0 To 4
For j = 0 To 1
Console.WriteLine("a[{0},{1}] = {2}", i, j, a(i, j))
Next j
Next i
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
a[0,0]: 0
a[0,1]: 0
a[1,0]: 1
a[1,1]: 2
a[2,0]: 2
a[2,1]: 4
a[3,0]: 3
a[3,1]: 6
a[4,0]: 4
a[4,1]: 8
Dynamic Arrays
Dynamic arrays are arrays that can be dimensioned and re-dimensioned as par the need of the
program. You can declare a dynamic array using the ReDim statement.
Where,
The Preserve keyword helps to preserve the data in an existing array, when you resize it.
arrayname is the name of the array to re-dimension.
subscripts specifies the new dimension.
Example:
Module arrayApl
Sub Main()
Dim marks() As Integer
ReDim marks(2)
marks(0) = 85
marks(1) = 75
marks(2) = 90
ReDim Preserve marks(10)
marks(3) = 80
marks(4) = 76
marks(5) = 92
marks(6) = 99
marks(7) = 79
marks(8) = 75
Console.WriteLine(“Index” & vbTab & “marks”)
For i = 0 To 10
Console.WriteLine(i & vbTab & marks(i))
Next i
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
Index marks
0 85
1 75
2 90
3 80
4 76
5 92
6 99
7 79
8 75
9 0
10 0
CONTROL STATEMENTS:
If Then Statement
If Then Else Statement
Nested If Then Else Statement
Select Case Statement
1. If Then Statement
If Then statement is a control structure which executes a set of code only when the given
condition is true.
Syntax:
If [Condition] Then
[Statements]
End If
In the above syntax when the Condition is true then the Statements after Then are executed.
Example:
Private Sub Button1_Click_1(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
If Val(TextBox1.Text) > 25 Then
TextBox2.Text = "Eligible"
End If
Description:
In the above If Then example the button click event is used to check if the age got using TextBox1
is greater than 25, if true a message is displayed in TextBox2.
Example:
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
If Val(TextBox1.Text) >= 40 Then
MsgBox("GRADUATED")
Else
MsgBox("NOT GRADUATED")
End If
End Sub
3. Nested If Then Else Statement
Nested If..Then..Else statement is used to check multiple conditions using if then else
statements nested inside one another.
Syntax:
If [Condition] Then
ElseIf [Condition] Then
[Statements]
ElseIf [Condition] Then
[Statements]
Else
[Statements]
End If
In the above syntax when the Condition of the first if then else is true, the second if then else is
executed to check another two conditions. If false the statements under the Else part of the first
statement is executed.
Example:
In the above syntax, the value of the Expression is checked with Expression1..n to check if the
condition is true. If none of the conditions are matched the statements under the Case Else is
executed.
Example:
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim c As String
c = TextBox1.Text
Select c
Case "Red"
MsgBox("Color code of Red is::#FF0000")
Case "Green"
MsgBox("Color code of Green is::#808000")
Case "Blue"
MsgBox("Color code of Blue is:: #0000FF")
Case Else
MsgBox("Enter correct choice")
End Select
End Sub
LOOPING STATEMENT
While End while
Do While Loop Statement
Do Loop While Statement
Do Loop Until Statement
For Next Loop Statement
In the above Do While Loop example the loop is continued after the value 64 to display 128 which
is false according to the given condition and then the loop exits.
In the above syntax the Statements are executed first then the Condition is checked to find if it is
true.
Example:
Private Sub Form1_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load
Dim cnt As Integer
Do
cnt = 10
MsgBox("Value of cnt is::" & cnt)
Loop While cnt <= 9
End Sub
Description:
In the above Do Loop While example, a message is displayed with a value 10 only after which the
condition is checked, since it is not satisfied the loop exits.
In the above syntax the Statements are executed until the Condition becomes false.
Example:
Private Sub Form1_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load
Dim X As String
Do
X$ = InputBox$("Correct Password Please")
Loop Until X$ = "Ranger"
End Sub
Description:
In the above Do Until Loop example, a input box is displayed until the correct password is typed.
For Next Loop Statement executes a set of statements repeatedly in a loop for the given
initial, final value range with the specified step by step increment or decrement value.
Syntax:
For counter = start To end [Step]
[Statement]
Next [counter]
In the above syntax the Counter is range of values specified using the Start ,End parameters. The
Step specifies step increment or decrement value of the counter for which the statements are
executed.
Example:
Private Sub Form1_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load
Dim i As Integer
Dim j As Integer
j = 0
For i = 1 To 10 Step 1
j = j + 1
MsgBox("Value of j is::" & j)
Next i
End Sub
Description:
In the above For Next Loop example the counter value of i is set to be in the range of 1 to 10 and is
incremented by 1. The value of j is increased by 1 for 10 times as the loop is repeated.
UNIT-II
PROCEDURES
Procedures are also used for implementing repeated tasks, such as frequently used
calculations.
The two types of procedures supported by Visual Basic .NET. They are
Subroutines or Procedure
functions
Modular Coding
The idea of breaking a large application into smaller, more manageable sections is not new
to computing.
Few tasks, programming or otherwise, can be managed as a whole.
The event handlers are just one example of breaking a large application into smaller tasks.
Some event handlers may required a lot of code.
You could calculate the net profit with the following statements, which will most likely
appear
behind a button’s event handler:
RetrievePOLines(productID)
Sum1 = SumQtyPrice()
Qty1 = SumQuantities()
RetrieveInvoiceLines(productID)
Sum2 = SumQtyPrice()
Net = (Sum2 – Sum1) / Qty1
The task is broken into smaller units, and each unit is implemented by a function or
subroutine.
The name of the procedure indicates the operationit performs. First, the RetrievePOLines()
subroutine retrieves quantities and purchase prices ofa specific product—the productID
argument—from a database. The SumQtyPrice() function multiplies the quantities by prices
at which they were sold and sums the results to get the total value paid for the purchase of a
specific product. This result is stored in the Sum1 variable. The SumQuantities() function
sums the unit quantities into the Qty1 variable.
Subroutines/Procedure
A subroutine is a block of statements that carries out a well-defined task.
Subroutine or procedure does not return any values.
A procedure is a group of statements that together perform a task when called.
The block of statements is placed within a set of Sub…End Sub statements and can be
invoked by name.
Syntax:
Example:
Module Module1
Sub SitDown()
MsgBox("This program expects that you are sitting down!")
End Sub
Sub Main()
SitDown()
End Sub
End Module
All variables declared within a subroutine are local to that subroutine. When the subroutine
exits, all variables declared in it cease to exist.
Procedure Program:-
Imports System.Console
Module Module1
Sub square(ByVal a As Integer)
Console.WriteLine("The Area of square is:" & (a * a))
End Sub
Sub rectangle(ByVal l As Integer, ByVal w As Integer)
Console.WriteLine("The Area of Rectangle is:" & (l * w))
End Sub
Sub circle(ByVal r As Integer)
Console.WriteLine("The Area of Circle is:" & (3.14 * r * r))
End Sub
Sub triangle(ByVal b As Integer, ByVal h As Integer)
Console.WriteLine("The Area of Triangle is:" & ((b * h) / 2))
End Sub
Sub Main()
Dim a, l, w, b, h, r As Integer
Console.WriteLine("")
Console.WriteLine("Enter the A value:")
a = Console.ReadLine()
Console.WriteLine("")
Console.WriteLine("Enter the L value:")
l = Console.ReadLine()
Console.WriteLine("")
Console.WriteLine("Enter the W value:")
w = Console.ReadLine()
Console.WriteLine("")
Console.WriteLine("Enter the B value:")
b = Console.ReadLine()
Console.WriteLine("")
Console.WriteLine("Enter the H value:")
h = Console.ReadLine()
Console.WriteLine("")
Console.WriteLine("Enter the R value:")
r = Console.ReadLine()
Console.WriteLine("")
Console.WriteLine("Prodecure")
Console.WriteLine("")
square(a)
Console.WriteLine("")
rectangle(l, w)
Console.WriteLine("")
circle(r)
Console.WriteLine("")
triangle(b, h)
Console.WriteLine("")
End Sub
End Module
Functions
A function is similar to a subroutine, but a function returns a result.
Subroutines perform a task and don’t report anything to the calling program; functions
commonly carry out calculations and report the result. Because they return values,
functions—like variables—have types.
Defining a Function
The Function statement is used to declare the name, parameter and the body of a function. The
syntax for the Function statement is:
Where,
Modifiers: specify the access level of the function; possible values are: Public, Private,
Protected, Friend, Protected Friend and information regarding overloading, overriding, sharing, and
shadowing.
FunctionName: indicates the name of the function
ParameterList: specifies the list of the parameters
ReturnType: specifies the data type of the variable the function returns
The value you pass back to the calling program from a function is called the return value,
and its type must match the type of the function. Functions accept arguments, just like
subroutines.
The statements that make up a function are placed in a set of Function…End Function
statements, as shown here:
Function NextDay() As Date
Dim theNextDay As Date
theNextDay = DateAdd(DateInterval.Day, 1, Now())
Return(theNextDay)
End Function
DateAdd() is a built-in function that adds a number of intervals to a date.
When you call a procedure, you must supply values for all the arguments specified in the
procedure’s definition and in the same order.
To call a procedure, you simply enter its name, followed by its arguments in parentheses:
The values of the arguments must match their declared type. If a procedure expects an
integer value, you shouldn’t supply a date value or a string.
If the procedure is a function, you must assign its return value to a variable so you can use it
from within your code.
The following statement creates the complete ISBN by calling the ISBNCheckDigit()
function:
The argument of the MsgBox() function needs a some explanation. It calls the ISBNCheck-
Digit() function, passing the ISBN as argument. Then it appends the check digit (which is the value
returned by the function) to the ISBN value and prints it. It is equivalent to the following statements,
which are simpler to read, but not nearly as common:
Functions are called by name, and a list of arguments follows the name in parentheses as shown:
Degrees = Fahrenheit(Temperature)
In this example, the Fahrenheit() function converts the Temperature argument (which presumably is
the temperature in degrees Celsius) to degrees Fahrenheit, and the result is assigned to the Degrees
Variable.
ARGUMENTS
Subroutines and functions aren’t entirely isolated from the rest of the application.
Most procedures accept arguments from the calling program.
Recall that an argument is a value you pass to the procedure and on which the procedure
usually acts.
Functions also accept arguments—in many cases, more than one.
The function Min(), for instance, accepts two numbers and returns the smaller one:
One of the most important issues in writing procedures is the mechanism used to pass
arguments.
The examples so far have used the default mechanism: passing arguments by value.
End Function
Function cylinder(ByVal r As Integer, ByVal h As Integer)
Return 3.14 * r * r * h
End Function
Function cone(ByVal r As Integer, ByVal h As Integer)
Return 1 / 3 * 3.14 * r * r * h
End Function
Function sphere(ByVal r As Integer)
Return 4 / 3 * 3.14 * r * r * r
End Function
Sub Main()
Dim a As Integer
Dim r, h As Integer
Console.WriteLine("Enter the a value:")
Console.WriteLine("")
a = Console.ReadLine()
Console.WriteLine("Enter the r value:")
Console.WriteLine("")
r = Console.ReadLine()
Console.WriteLine("Enter the h value:")
Console.WriteLine("")
h = Console.ReadLine()
Console.WriteLine("")
Console.WriteLine("Functions:-")
Console.WriteLine("")
Console.WriteLine("The Volume Of Cube:" & cube(a))
Console.WriteLine("")
Console.WriteLine("The Volume Of Cylinder:" & cylinder(r, h))
Console.WriteLine("")
Console.WriteLine("The Volume Of Cone:" & cone(r, h))
Console.WriteLine("")
Console.WriteLine("The Volume Of Sphere:" & sphere(r))
Console.WriteLine("")
End Sub
End Module
Passing Arguments by Reference
Passing arguments by reference gives the procedure access to the actual variable.
The calling procedure passes the address of the variable in memory so that the procedure can
change its value permanently.
Start a new Visual Basic project and enter the following function definition in the form’s
code
window:
This simple function adds two numbers and then sets them to zero.
Next, place a Command button on the form and enter the following code in the button’s Click event:
The keyword struct can be used to declare a structure. The general form of a structure
declaration in VB.NET is as follows.
Syntax:
Where the modifier can be private, public, internal or public. The structure is the required keyword.
For example
Structure MyStruct
Public x As Integer
Public y As Integer
End Structure 'MyStruct
The objects of a strcut can be created by using the new operator as follows.
Dim ms As New MyStruct()
The individual members of a struct can be accessed by using the dot (.) operator as showing
below.
ms.x = 10
ms.y = 20
Remember that unlike classes, the strcut object can also be created without using the new
operator.
Dim ms As MyStruct
A struct in VB.NET can contain fields. These fields can be declared as private, public, internal.
Remember that inside a struct, we can only declare a field. We can't initialize a field inside a
struct. However we can use constructor to initialize the structure fields.
The following is not a valid VB.NET struct and the code will not compile, since the fields inside
the structure are trying to initialize.
Structure MyStruct
Private x As Integer = 20
Private y As Integer = 20
End Structure 'MyStruct
Structures Vs Classes
Structures Classes
Value type Reference type
Supports data members, code members Supports data members, code members
(methods) and events (methods) and events
Can not inherit Supports inheritance
Preferable when you perform large number Preferable when you need to initialize
of operations on each instance one or more members upon creation
Sub Main()
Dim san As New Employee()
'creating an instance of Employee
san.EmpName = "Sandeep"
san.EmpDesignation = "Software Developer"
san.EmpCity = "Sydney"
san.EmpSal = 60000
san.EmpId = 2707
'assigning values to member variables
WriteLine("EmpName" + " " + san.EmpName)
WriteLine("EmpDesignation" + " " + san.EmpDesignation)
WriteLine("EmpCity" + " " + san.EmpCity)
WriteLine("EmpSalary" + " " + san.EmpSal.ToString)
WriteLine("EmpID" + " " + san.EmpId.ToString)
'accessing member variables with the period/dot operator
Read()
End Sub
End Module
The output of above code is the image below.
Collection classes are specialized classes for data storage and retrieval.
These classes provide support for stack, queue, list and hash table.
Array List
Array List is one of the most flexible data structure from VB.NET Collections.
ArrayList contains a simple list of values and very easily we can add, insert , delete , view
etc. to do with ArrayList.
It is very flexible because we can add without any size information that is it grow
dynamically and also shrink.
Unlike array you can add and remove items from a list at a specified position using an index
and resize the array itself automatically.
It also allow dynamic memory allocation add, search, and sort items in the list.
Property Description
Capacity Gets or sets the number of elements that the ArrayList can contain.
Count Gets the number of elements actually contained in the ArrayList.
IsFixedSize Gets a value indicating whether the ArrayList has a fixed size.
IsReadOnly Gets a value indicating whether the ArrayList is read-only.
Item Gets or sets the element at the specified index.
The following table lists some of the commonly used methods of the ArrayList class:
Syntax : ArrayList.add(Item)
ItemList.Add("Item4")
Syntax : ArrayList.insert(index,item)
ItemList.Insert(3, "item6")
Syntax : ArrayList.Remove(item)
ItemList.Remove("item2")
Syntax : ArrayList.RemoveAt(index)
ItemList.RemoveAt(2)
Syntax : ArrayListSort()
The following VB.NET source code shows some function in ArrayList
Example 2:
Sub Main()
Dim al As ArrayList = New ArrayList()
Dim i As Integer
Console.WriteLine("Adding some numbers:")
al.Add(45)
al.Add(78)
al.Add(33)
al.Add(56)
al.Add(12)
al.Add(23)
al.Add(9)
Console.WriteLine("Capacity: {0} ", al.Capacity)
Console.WriteLine("Count: {0}", al.Count)
Console.Write("Content: ")
For Each i In al
Console.Write("{0} ", i)
Next i
Console.WriteLine()
Console.Write("Sorted Content: ")
al.Sort()
For Each i In al
Console.Write("{0} ", i)
Next i
Console.WriteLine()
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
Hash Table:-
The Hashtable class represents a collection of key-and-value pairs that are organized based
on the hash code of the key. It uses the key to access the elements in the collection.
A hashtable is used when you need to access elements by using key, and you can identify a
useful key value. Each item in the hashtable has a key/value pair. The key is used to access the items
in the collection.
The following table lists some of the commonly used properties of the Hashtable class:
Property Description
Count Gets the number of key-and-value pairs contained in the Hashtable.
IsFixedSize Gets a value indicating whether the Hashtable has a fixed size.
IsReadOnly Gets a value indicating whether the Hashtable is read-only.
Item Gets or sets the value associated with the specified key.
Keys Gets an ICollection containing the keys in the Hashtable.
Values Gets an ICollection containing the values in the Hashtable.
The following table lists some of the commonly used methods of the Hashtable class:
Syntax : HashTable.Add(Key,Value)
Synatx : HashTable.ContainsKey(key)
Key : The Key value for search in HahTable
Synatx : HashTable.ContainsValue(Value)
Syntax : HashTable.Remove(Key)
When you execute this program it add seven weekdays in the hash table and display the
item 5. Then it check the item "Tue" is existing or not . Next it remove the third item from Hash
Table. Finally it displays all item exist in the Hash Table.
Example:
When the above code is compiled and executed, it produces the following result:
006: M. Arif
007: Ritesh Saikia
008: Nuha Ali
003: Joe Holzner
002: Abida Rehman
004: Mausam Banazir Nur
001: Zara Ali
005: M. Amlan
Sorted List
The SortedList class represents a collection of key-and-value pairs that are sorted by the keys
and are accessible by key and by index.
A sorted list is a combination of an array and a hashtable.
It contains a list of items that can be accessed using a key or an index.
If you access items using an index, it is an ArrayList, and if you access items using a key, it
is a Hashtable.
The collection of items is always sorted by the key value.
The following table lists some of the commonly used properties of the SortedList class:
Property Description
Capacity Gets or sets the capacity of the SortedList.
Count Gets the number of elements contained in the SortedList.
IsFixedSize Gets a value indicating whether the SortedList has a fixed size.
IsReadOnly Gets a value indicating whether the SortedList is read-only.
Item Gets and sets the value associated with a specific key in the SortedList.
Keys Gets the keys in the SortedList.
Values Gets the values in the SortedList.
The following table lists some of the commonly used methods of the SortedList class:
Example:
Module collections
Sub Main()
Dim sl As SortedList = New SortedList()
sl.Add("001", "Zara Ali")
sl.Add("002", "Abida Rehman")
sl.Add("003", "Joe Holzner")
sl.Add("004", "Mausam Benazir Nur")
sl.Add("005", "M. Amlan")
sl.Add("006", "M. Arif")
sl.Add("007", "Ritesh Saikia")
If (sl.ContainsValue("Nuha Ali")) Then
Console.WriteLine("This student name is already in the list")
Else
sl.Add("008", "Nuha Ali")
End If
' Get a collection of the keys.
Dim key As ICollection = sl.Keys
Dim k As String
For Each k In key
Console.WriteLine(" {0} : {1}", k, sl(k))
Next k
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
When you define a class, you define a blueprint for a data type. This doesn't actually define any
data, but it does define what the class name means, that is, what an object of the class will consist of
and what operations can be performed on such an object.
Objects are instances of a class. The methods and variables that constitute a class are called
members of the class.
Class Definition
A class definition starts with the keyword Class followed by the class name; and the class body,
ended by the End Class statement. Following is the general form of a class definition:
Where,
The following example demonstrates a Box class, with three data members, length, breadth and
height:
Module mybox
Class Box
Public length As Double ' Length of a box
Public breadth As Double ' Breadth of a box
Public height As Double ' Height of a box
End Class
Sub Main()
Dim Box1 As Box = New Box() ' Declare Box1 of type Box
Dim Box2 As Box = New Box() ' Declare Box2 of type Box
Dim volume As Double = 0.0 ' Store the volume of a box here
' box 1 specification
Box1.height = 5.0
Box1.length = 6.0
Box1.breadth = 7.0
' box 2 specification
Box2.height = 10.0
Box2.length = 12.0
Box2.breadth = 13.0
'volume of box 1
volume = Box1.height * Box1.length * Box1.breadth
Console.WriteLine("Volume of Box1 : {0}", volume)
'volume of box 2
volume = Box2.height * Box2.length * Box2.breadth
Console.WriteLine("Volume of Box2 : {0}", volume)
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
From the Toolbox, drag a Button control onto the form. Change its Text property to Hello, world!
and its Name property to btnSayHello. Resize your button so that it looks similar to the one shown
below:
Private Sub btnSayHello_Click(ByVal sender As System.Object, _ ByVal e As
System.EventArgs) Handles btnSayHello.Click
‘Display a MessageBox
MessageBox.Show(“Hello, world!”, Me.Text)
End Sub
The first job is to start a new project and build a form. This form will contain a multiline text
box where you can enter text. It will also contain two radio buttons that will give you the option of
counting either the words or the number of characters in the text box.
1. Select File New Project from the Visual Studio 2005 menu and create a new Windows
Application project. Enter a project name of Word Counter and click OK.
2. Click on Form1 and, in the Properties window, set the Size property to 424, 312, the StartPosition
property to CenterScreen, and the Text property to Word Counter.
3. Drag a TextBox control from the Toolbox and drop it on the form. Now change the properties of
the text box as shown in the following list:
4. To tell the user what to do with the form, you add a label. Select the Label control from the
Toolbox, drag and drop it just above the text box. Change the Text property to Enter some text into
this box.
Strictly speaking, unless you’re going to need to talk to the control from your code, you don’t need
to change its Name property. With the text box, you need to use its properties and methods to make
the application work. However, the label is just there for esthetics, so you don’t need to change the
name for Label1.
5. Your application is going to be capable of counting either the characters the user entered or the
number of words. To allow the user to select the preferred count, you use two radio buttons. Draw
two RadioButton controls onto the form next to each other below the text box. You need to refer to
the radio buttons from your Visual Basic .NET code, so change the properties as shown in the
following lists:
6. As the user types, you’ll take the characters that the user enters and count up the words or
characters as appropriate. You want to pass your results to the user, so add two new Label controls
next to the RadioButton controls that you just added.
7. The first Label control (marked Label2) is just for esthetics, so change its Text property to The
results are:. The second Label control will report the results, so you need to give it a name. Set the
Name property as lblResults and clear the Text property.
8. You also need a Button control that will show a message box, so add a Button control to the form
and align it to the bottom right of the text box. You don’t strictly need this because the user can read
the results on the form, but it will illustrate a couple of important points. Change the Name property
to btnShowMe and the Text property to Show Me!. Your completed form should look similar to the
one shown here:
9. Now that you have the controls laid out on your form the way you want it, you can make sure you
keep it that way. Make sure you select one of the controls and not the actual form, and then select
Format Lock Controls from the menu. This sets the Locked property of each of the controls to
True and prevents them from accidentally being moved, resized, or deleted.
Visual Basic .NET provides several built-in dialog boxes that help you provide a rich user
interface in your front-end applications.
These dialog boxes provide the same common user interface that is found in most Windows
applications.
They also provide many properties and methods that allow you to customize these dialog
boxes to suit your needs while still maintaining the standard look of Windows applications.
Using MessageBox
In the day-to-day operation of a computer, you have seen message boxes that display
one of the icons shown in below figure.
The first icon this figure has three names: Error, Hand, and Stop.
The second icon has only one name: Question.
The third icon has two names: Exclamation and Warning.
The final icon has two names: Asterisk and Information.
Available Icons
Member Name Description
Asterisk Specifies that the message box displays an information icon
Information Specifies that the message box displays an information icon
Error Specifies that the message box displays an error icon
Hand Specifies that the message box displays an error icon
Stop Specifies that the message box displays an error icon
Exclamation Specifies that the message box displays an exclamation icon
Warning Specifies that the message box displays an exclamation icon
Question Specifies that the message box displays an exclamation icon
None Specifies the message box will not display any icon
Available Buttons
Member Name Description
AbortRetryIgnore Specifies that the message box displays Abort, Retry, and Ignore
buttons
OK Specifies that the message box displays an OK button
OKCancel Specifies that the message box displays OK and Cancel buttons
RetryCancel Specifies that the message box displays Retry and Cancel buttons
YesNo Specifies that the message box displays Yes and No buttons
YesNoCancel Specifies that the message box displays Yes, No, and Cancel buttons
Default Buttons
Member Name Description
Button1 Specifies that the first button in the message box should be the default
button
Button2 Specifies that the second button in the message box should be the
default button
Button3 Specifies that the third button in the message box should be the
default button
Show Method Syntax
You call the Show method to display the message box.
MessageBox.Show(message text)
MessageBox.Show(message text, caption)
MessageBox.Show(message text, caption, buttons)
MessageBox.Show(message text, caption, buttons, icon)
MessageBox.Show(message text, caption, buttons, icon, default button)
The following table shows the available members in the DialogResult enumeration.
You can move a form around, resize it, and even cover it with other forms. You do with the
mouse, or with the keyboard through the Control menu.
they are “intelligent” objects that are aware of the controls placed on them and can actually
manipulate the controls at runtime
Clicking the icon on the left end of the title bar opens the Control menu, which contains the
Commands. On the right end of the title bar are three buttons: Minimize, Maximize, and Close.
Clicking these buttons performs the associated function. When a form is maximized, the
maximize button is replaced by the Restore button. When clicked, this button resets the form to the
size and position before it was maximized.
The Restore button is then replaced by the Maximize button.
Command Effect
Restore Restores a maximized form to the size it was before it was maximized; available only if
the form has been maximized
Move Lets the user move the form around with the mouse
Size Lets the user resize the form with the mouse
Minimize Minimizes the form
Maximize Maximizes the form
Close Closes the current form
Forms in Visual Basic.net 2008 is so important to the user as it is the application for the user. So
identifying and displaying forms is vital to the usability of an application. Even the developers need
to alter the properties to manage the forms in VB.net.
Following table lists some important Properties of Forms in Visual Basic.net 2008.
Properties Description
BackColor Set's the background color for the form
BackgroundImage Set's the background image for the form
Set the cursor image when it hovers over the
Cursor
form.
Specifies whether to accept the data dragged and
AllowDrop
dropped onto the form.
Font Get or sets the font used in the form
Locked Specifies whether the form is locked.
FormBorderStyle Get or set border style of a form
Text Provide the title for a Form Window
Determines whether the ControlBox is available
Control Box by clicking the icon on the upper left corner of the
window.
Specifies icon for the window on the upper left
Icon
corner.
Sets the type of mouse pointer to be displayed
MousePointer
when hovered over an specific area.
Get or sets the form button if the enter key is
AcceptButton
pressed.
Language Specifies the loaclized language.
Autoscroll Specifies whether to enable auto scrolling.
Specifies whether to display the maximize option
MaximizaBox
in the caption bar of the form.
Defines whether the form is a container of
IsMDIChild
Multiple Document Interface(MDI) child form.
Specifies whether to display the minimize option
MinimizeBox
in the caption bar of the form.
This declaration must appear in Form1 and must be placed outside any procedure.
Form2 from within Form1, execute the following statement:
frm.Show
Show / Hide Forms
Form in Visual Basic.net 2008 are displayed and hidden using two different methods.To display
a form the Show() method is used and to hide a form Hide() method is used.
Show Method:
This method is used to display the form on top of all other windows even if it is loaded or not loaded
into the memory.
Syntax:
FormName.Show
or
FormName.Show(1,)
In the above syntax, the Show method can also have argument values 0 or 1 for Modeless or Modal
forms. By default this methods modeless or normal forms, but the modal forms more interactive.
Hide Method:
This method hides a form object from the screen, still with the object being loaded in the memory.
Syntax:
FormName.Hide
Example:
Public Class Form1
End Sub
End Sub
End Class
Description:
In the above example, two forms Form1, Form2 are used. An image is added to Form2 using the
the click event of Button1 and Button2 the form is shown or hidden. Thus you can show or hide the
forms.
Load Method:
This method is used to load a form into the memory, but will not display the form.
Syntax:
Load FormName
UnLoad Method:
Syntax:
UnLoad FormName
This is the control itself.If you click on this(it’s highlighted above) ,you’ll see that the
Properties box on the right changes.There are many properties for the control.
To start building your menu,click inside the area that says”Type here”Type the world file:
Now press the enter key on your keyboard.your menu will look like this:
To create item on your File menu.click inside the Type Here box,Enter the world New,and press
the
Enter key on your keyboard again.Your menu will then look like this:
Add an “Open” and a “Save” item to your menu in the same way.
It should look like this:
The final item we’ll add our menu is an”Exit” item.But you can add a
To add a separator,click inside the blue “Type here” Box.Instead of typing a letter,type the
minus character”-”(in between the “0” key and the”+/” on your key board)When you hit
your return key,you’ll see the separator appear:
Click inside the “Type here” area,and an Exit(or Quit) item.Click back on your form,away
from the menu,to finish off.You should now have a file.
The IDE provides a visual tool for designing menus, and then you can program their Click
event
handlers. each item (command) in a menu is represented by a MenuItem object, you can control the
application’s menus from within your code by manipulating the properties of the MenuItem objects.
Double-click the MainMenu icon on the Toolbox. The MainMenu control will be added to
the
form, and a single menu command will appear on your form.
Its caption will be Type Here. If you don’t see the first menu item on the Form right away,
select the MainMenu control in the Components tray below the form. Do as the caption says; click it
and enter the first command’s caption,File As soon as you start typing, two more captions appear:
one on the same level (the second command of the form’s main menu, representing the second pull-
down menu) and another one below File (representing the first command on the File menu). Select
the item under File and enter the string New.
As soon as you start entering the caption of a menu or menu item, more items appear to the left and below the
current item.
Enter the remaining items of the File menu—Open, Save, and Exit—and then click
somewhere
on the form. All the temporary items (the ones with the Type Here caption) will disappear, and the
menu will be finalized on the form. At any point, you can add more items by right-clicking one of
the existing menu items and selecting Insert New.
Caption Name
File FileMenu
New FileNew
Open FileOpen
Save FileSave
Exit FileExit
Edit EditMenu
Copy EditCopy
Cut EditCut
Paste EditPaste.
Add method
Adds a new element to the Controls collection. In effect, it adds a new control on
the current form.
The Add method accepts a control as argument and adds it to the collection. Its syntax is:
Controls.Add(controlObj)
where controlObj is an instance of a control.
Remove method
Removes an element from the Controls collection.
It accepts as argument either the index of the control to be removed, or a reference to the
control to be removed (a variable of the Control type that represents one of the controls on the
form). The syntax of these two forms is:
Me.Controls.Remove(index)
Me.Controls.Remove(controlObj)
Count property
Returns the number of elements in the Controls collection. The number of
controls on the current form is given by the expression
Me.Controls.Count
All method
Returns all the controls on a form (or in a container control) as an array of the
System.WinForms.Control type.
You can iterate through the elements of this array with the usual methods exposed by the
Array class.
Clear method
TEXTBOX CONTROL:
The Textbox control is mainly used to accept the text form keyboard during runtime.
Three important properties of this control are Name, Text, and Multiline
. The Name property’s value is used in program code. The Text property’s value appears
directly in the textbox.
When we place a TextBox control on the form, the default value of Name property is TextBox
1. The default value of Text property is also TextBox1.
The default value of Multiline property is False. By default, we can place only one line of tet inside
a textbox.
If we wish to place two or more lines inside a textbox, we have to set the Multiline property
to True. The properties of TextBox control are discussed in the following table.
LABEL CONTROL:
Label control is a simple and at the same time useful control.
This control is used to label various item on a form. Some important properties of this
control are Name, text, Location, Size, BackColor, ForeColor, Font and Enabled.
As in the case of TextBox control, Name property’s value is used in program code. The
property’s value appears directly in the label.
BUTTON CONTROL:
The Button control looks like a push button on a TV panel. This control is used for issuing
commends.
It is one of the most frequently used controls.
Some important properties of this control are Name, Text, and FlatStyle.
As usual, the Name property’s value is used in the program cod and the Text property’s
value appears directly on the button.
RADIOBUTTON CONTROL:
The Radio Button control looks and behaves very much like a button in old-fashioned car
radio.
Radio button were known as option-button in Visual Basic 6. We use this control in a
project when we expect the user to choose only one item among many available items.
Some important properties of the Radio Button control are Name, Text, and Checked.
As usual, the Name property’s value is used in the program code and the Text property’s
value appears to the fight of the radiobuton.
Two possible values of Checked property are True and False. When a radio button is
clicked, its Checked property will be set to True.
EXAMPLE PROGRAM
End If
If Blue. Checked Then
InfoLabel. Text = “U have selected Blue Exterior”
End If
If White. Checked Then
InfoLabel. Text = “U have selected White Exterior”
End If
CHECKBOX CONTROL:
The Checkbox control represents a checkable entity on the form. We checkboxes in a project
when we expect the user to choose a set of items among many available items.
`Some important properties of this control are Name, Text, and Checked.
As usual, the Name property’s value is used in the program code and the Text property’s
value appears to the right of Checkbox.
GROUPBOX CONTROL:
The Group Box control was known as Frame control in Visual Basic6.
We use this control to group the related controls. Suppose that we place ten radio buttons
on a form. In such a case, we can select only one of these ten radio buttons.
On the other hand, if we place the first five radio buttons inside a group box and the
remaining five radio buttons inside another group box,
we shell select one radio button form the first group box and another radio button f rom the
second group box.
EXAMPLE
1. CREATE A NEW Windows application and name it GroupBox Demo. Now, the form will
open in the designer mode.
2. In this example, we will place a Button control GroupBox control, four RadioButton
control, and two Label control on the form. We will change the name and Text properties of
the Button, GroupBox, Label, and Radiobutton controls. We will change the properties as
show in the following table:
3. Double-Click the Display Button control in order to create the event-handling method for
the Click event of this control.
4. Now, the template for the event-handling method will appear in the usual manner. Add the
code show in boidface below in the event-handling method so that the desired text will
appear within a label when the DisplayButton control is clicked.
LISTBOX CONTROL;
We have so far discussed three button-centric controls, namely the Button control,
Checkbox control, and Radio Button control. We will now discuss three list-selection-centric
controls, namely the List Box control, the CheckedListBox control, and Combo Box control.
EX;
Private Sub DisplayButton_Click(ByVal sender As System. Object, ByVal e As System.
EventArgs) Handles DisplayButton.Click
If ComputerMakerList.SelectedItem <> Nothing Then
InfoLabel. Text = “ u have selected the company : “ “ & computerMakerList. SelectedItem
End If
You simply add them to the project by double-clicking their icons in the Toolbox;
A new icon appears in the components tray of the form, just below the Form Designer.
OpenFileDialog - Lets users select a file to open. It also allows the selection of multiple files
for applications that must process many files at once.
SaveFileDialog - Lets users select or specify the path of a file in which the current document
will be saved.
FolderBrowserDialog - Lets users select a folder (an operation that can't be performed with
the OpenFileDialog control).
ColorDialog - Lets users select a color from a list of predefined colors or specify custom
colors.Use to apply the currently selected font to the text without closing the dialog box.
You must first add an instance of the appropriate control to your project.
Then you must set some basic properties of the control through the Properties window.
Most applications set the control's properties from within the code because common dialogs
interact closely with the application.
When you call the Color common dialog, for example, you should preselect a color from
within your application and make it the default selection on the control.
When prompting the user for the color of the text, the default selection should be the current
setting of the control's Fore Color property.
As soon as you call the Show Dialog method, the corresponding dialog box appears
onscreen, and the execution of the program is suspended until the box is closed.
Using the Open, Save, and Folder Browser dialog boxes, users can traverse the entire
structure of their drives and locate the desired filename or folder.
When the user clicks the Open or Save button, the dialog box closes and the program's
execution resumes.
The code should read the name of the file selected by the user through the Filename
property and use it to open the file or store the current document there.
The folder selected in the FolderBrowserDialog control is returned to the application through
the Selected Path property.
Here is the sequence of statements used to invoke the Open common dialog and retrieve the
selected filename:
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
filename = OpenFileDialog1.FileName
End If
OpenFileDialog1.FileName = "C:\WorkFiles\Documents\Document1.doc"
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
filename = OpenFileDialog1.FileName
End If
you can invoke the Color dialog box and read the value of the selected color by using the
following statements:
ColorDialog1.Color = TextBox1.BackColor
If ColorDialog1.ShowDialog = DialogResult.OK Then
TextBox1.BackColor = ColorDialog1.Color
End If
The Show Dialog method is common to all controls. The Title property is also common to all
controls and it's the string displayed in the title bar of the dialog box.
ColorDialog1.Title = "Select Drawing Color"
Rich Textbox
Rich Textboxes are similar to Textboxes but they provide some advanced features over the
standard Textbox. Rich Textbox allows formatting the text, say adding colors, displaying particular
font types
The Rich Textbox, like the Textbox is based on the Textbox Base class which is based on the
Control class.
These Rich Textboxes came into existence because many word processors these days allow
us to save text in a rich text format.
With Rich Textboxes we can also create our own word processors. We have two options
when accessing text in a Rich Textbox, text and rtf (rich text format). Text holds text in normal text
and rtf holds text in rich text format. Image of a Rich Textbox is shown below.
RichTextBox Event The default event of RichtextBox is the TextChanged event which looks like
this in code:
End Sub
Code Samples
The files which we create using the Save File method is saved in the bin directory of the
Windows Application.
You can view output of the above said code in the image above.
Error Handling and Debugging in VB .NET
Debugging your code is something you will need to do
. Unless you write perfect code every time, there's no getting away from it.
Types of Error
Programming errors are generally broken down into three types: Design-time, Runtime, and
Logic errors.
A Design-time error is also known as a syntax error. These occur when the environment
you're programming in doesn't understand your code.
These are easy to track down in VB.NET, because you get a blue wiggly line pointing them
out.
If you try to run the programmer, you'll get a dialogue box popping up telling you that there
were Build errors.
Runtime errors are a lot harder to track down. As their name suggests, these errors occur
when the programmer is running.
An example is trying to access a file that doesn't exist.
Runtime errors usually cause your programmer to crash. If and when that happens, you get
the blame. After all, you are the programmer, and you should write code to trap runtime errors.
If you're trying to open a database in a specific location, and the database has been moved, a
Runtime error will occur. It's your job to predict a thing like this, and code accordingly.
Logic errors also occur when the programmer is running.
They happen when your code doesn't quite behave the way you thought it would. A classic
example is creating an infinite loop of the type "Do While x is greater than 10".
If x is always going to be greater than 10, then the loop has no way to exit, and just keeps
going round and round. Logic errors tend not to crash your programmer.
But they will ensure that it doesn't work properly.
Design Time Errors in VB .NET
Design time errors, remember, are syntax errors. It's when VB .NET hasn't understood what you
have typed. If that isn't clear, a few examples should explain it beter. So do the following:
Create a new Windows project
Add a button and textbox to your form
Leave the Name properties on the defaults of Button1 and Textbox1
Double click your button to access its code, and type the following:
Textbox2.Text = "Debug"
When you finish typing the line, VB.NET puts a blue wiggly line under Textbox2:
If you hold your mouse over Textbox2, you'll see a yellow tool tip appear, like the
following:
The error is occurring because you don't have a textbox called Textbox2. You'll also see this
same "Not declared" error if you try to set up a variable on the fly
As an example, change your code to this:
strText = "Debug"
TextBox1.Text = strText
Here, we are trying to put the word "Debug" into a variable called strText.
We then want to assign this variable to the Text property of Textbox1.
However, VB.NET protests about this, and puts a wiggly line under all occurrences of
strText:
Hold your mouse over the variable strText and you'll see the "not declared" tip again:
The problem this time is that we haven't declared the variable strText. Change the code to
this:
Dim strText As String
strText = "Debug"
TextBox1.Text = strText
Now that we have declared a variable, the wiggly lines will go away. If we added the variable
declaration in the wrong place, however, the wiggly lines would come back. Change you code to
this:
strText = "Debug"
TextBox1.Text = strText
Dim strText As String
If you have the Error List window open, you'll see a report of your error (If you can't see
the Task List window, from the menu bars click View > Other Windows > ErrorList):
The description of the error is "Local variable 'strText' cannot be referred to before it is
declared". If you double click the icons on the left, VB.NET will highlight the error in your code.
Move the Dim … Line back to the top, and not only do the blue wiggly lines go away, but
the Task List will be erased.
Design-time errors like the one above can be quite straightforward to correct.
Others can be quite difficult, and you'll see the blue wiggly line but not understand how to
correct the error.
The Task List should be your first port of call when faced with such an error.
This lesson is part of an ongoing tutorial. The first part is here: Design Time Errors
Runtime errors are a lot harder than Design Time errors to track down. As their name
suggests, these errors occur when the programme is running.
Runtime errors are the ones that crash your programme. A simple way to crash a programme
is to divided by zero. Change the code for your button to this, and try it out:
Num1 = 10
Num2 = 0
The CInt( ) part means Convert to an Integer. We're just making sure to convert the answer
to the sum into a number. But run your programmed and test it out.
What happens is that you'll get the following error message popping up:
Click the Break button, and then stop your programmer from running.
VB.NET has a inbuilt class that deals with errors. The Class is called Exception. When an
exception error is found, an Exception object is created.
The coding structure VB.NET uses to deal with such Exceptions is called the Try … Catch
structure
.
In the coding area for your button, type the word Try. Then hit the return key on your
keyboard. VB.NET completes the rest of the structure for you:
Try
Catch ex As Exception
End Try
The Try word means "Try to execute this code". The Catch word means "Catch any errors
here". The ex is a variable, and the type of variable it is is an Exception object.
Move your line of code from the previous section to the Try part:
Try
rt1.LoadFile("C:\test10.txt", RichTextBoxStreamType.PlainText)
Catch ex As Exception
End Try
When you run your programmer, VB will Try to execute any code in the Try part. If
everything goes well, then it skips the Catch part.
However, if an error occurs, VB.NET jumps straight to Catch. Add the following to your
Catch part:
MsgBox(ex.Message)
Your coding window should look like
this:
Because ex is an object variable, it now has its own Properties and methods. One of these is
the Message property. Run your programmer and test it out. Click your button. You should see the
following error message:
The message is coming from the "additional Information" section of the error message we
saw earlier, the one we didn't handle.
But the point about this new message box is that it will not crash your programmer.
You have handled the Exception, and displayed an appropriate message for the user.
If you know the kind of error that a programmer might throw, you can get what Type it is
from the Error message box you saw earlier. This one:
Click the View Details links under Actions to see the following:
The first line tells us the Type of Exception it is:
System.IO.FileNotFoundException
You can add this directly to the catch part. Previously, you were just catching any error that
might be thrown:
Catch ex As Exception
But if you know a "file not found" error might be thrown, you can add that to the Catch line,
instead of Exception:
Catch ex As System.IO.FileNotFoundException
You can keep the Exception line as well. (You can have as many Catch parts as you want.) This will
Catch any other errors that may occur:
Try
rt1.LoadFile("C:\test10.txt", RichTextBoxStreamType.PlainText)
Catch ex As System.IO.FileNotFoundException
MsgBox(ex.Message)
Catch ex As Exception
MsgBox(ex.Message)
End Try
There is one last part of the Try … Catch Statement that VB.NET doesn't add for you -
Finally:
Try
Catch ex As Exception
Finally
End Try
The finally part is always executed, whether an error occurs or not. You typically add a finally
part to perform any cleanup operations that are needed. For example, you may have opened a file
before going into a Try … Catch Statement. If an error occurs, the file will still be open. Whether an
error occurs or not, you still need to close the file. You can do that in the finally part.
But Microsoft advice that you always use Try … Catch Statements in your code. However,
throughout the rest of this course, for convenience sake, we won't be using them much. Even when
we should be. But that's no excuse for you not to use them!
Logic Errors in VB .NET
This lesson is part of an ongoing tutorial. The first part is here: Design Time Errors
The third category of errors are the Logic errors. These can be thought of as coding errors.
Your coding errors. They can be quite tricky to track down, and have you tearing your hair out with
frustration.
Dim x As Integer
Dim y As Integer
Dim answer As Integer
x = 10.5
y=3
answer = x * y
TextBox1.Text = answer
When you've added the code to your button, run your programme and test it out. Before you
click the button, what answer did you expect to get?
You'd think that 10.5 multiplied by 3 would give you the answer 31.5. Click your button. The
answer that appears in your textbox is 30!
NOTE: Visual Basic .NET or Visual Basic 2005 retains the "On Error Goto" syntax for backward
compatibility. You can still use this syntax in Visual Basic .NET or Visual Basic 2005 code.
However, you cannot combine structured exception handling and On Error statements within the
same procedure. When you write new code, Microsoft recommends that you use structured
exception handling.
The Try and End Try statements are required. The Catch and Finally statements are not
required, though you must include at least one of them in your code.
You can also specify multiple Catch statements so that each Catch block handles a specific
error.
Catch an Exception
1. Open the Console Application project that you created in the previous section.
2. In the Sub Main procedure, replace the code that you copied in the previous section with the
following code:
3. Dim a As Integer = 2147483647
4. Dim b As Integer = 0
5. Dim c As Integer = 0
6.
7. Try
8. a += 1
9. Catch exc As DivideByZeroException
10. Console.WriteLine("Error: Divide by zero")
11. Catch exc As OverflowException
12. Console.WriteLine("Error: Overflow")
13. Finally
14. Console.ReadLine()
15. End Try
This code includes two Catch blocks: one to catch the previous divide by zero
16. On the Debug menu, click Start to run the application. The Console window displays the
following error message:
17. Error: Overflow
18. Close the Console window.
19. Because you cannot always anticipate every error that may occur, you can add a Catch all
block for unanticipated exceptions. For example, add the following code before the Finally
statement to catch any unanticipated errors and display the appropriate error message:
20. Catch exc As Exception
21. Console.WriteLine("Error: " & exc.Message)
22. On the File menu, click Close Solution.
Throw an Exception
Structured exception handling uses the Catch statement to catch an exception. Structured
exception handling also provides a way to throw an exception
For example, it is useful to throw an exception when you perform data validation inside a
Property Set procedure because you may want to throw an error if a business rule is violated.
Catch an Exception
Module Module1
Sub Main()
Dim a As Integer = 0
Dim b As Integer = 0
Dim c As Integer = 0
Try
a = b \ c
Catch exc As Exception
Console.WriteLine("A run-time error occurred")
Finally
Console.ReadLine()
End Try
End Sub
End Module
Imports System.data
Public class from1
Private sub btnLoad_Click(ByVal sender As System.Object,ByVal e As
System.EvetArgs)Handles btnLoad.Click
Dim con As New OleDb.OleDbConnection
End sub
End class
Setting a connection stringing:
There are properties and methods associated with the connection object.
We want to start and with the connection property.
We need to pass two things to our new connection object; the technology we want to
use to do the connecting to our database; and where the database is. The technology is
called the provider; and you use “data source” to specify where your database is.
Con.connectionstring=”provider=Microsoft.jet.OLEDB.4.0;data source=c:\addressbook.mdb”
Opening the connection:
Now that we have a connectionstring , we can go ahead and open the database.this is quite
easy-just use the open method of the connection object:con.open()
Once open,the connection has to be closed again.this time, just use the close method:
Con.close()
Add the following four lines to your code:
Con.open()
Msgbox(“a connection to the database is now open”)
Con.close()
LOGICAL OPERATION:
Three logical operator AND,OR,NOT. Using AND both condition in the WHERE clause must
be True; when using OR, at least one of the conditions should be True and when using NOT, the
value of the clause flips from True and False.
ORDER BY CLAUSE:
Arrange the records in an order in the dataset.
SELECT * FROM Customers ORDER BY customerID Desc
You can also retrieve the record arranged in the descending order of
CustomerID from the Cutomer’s table.
AS CLAUSE:
When you are accessing records from a table, you can refer the fields with some more
descriptive names using AS clause.
SELECT ContactName AS Name FROM Customers
GROUP BY CLAUSE:
You can group records using GROUP BY clause.
SELECT * FROM Customers GROUP BY city
HAVING CLAUSE:
You can specify additional criteria for the records you want to retrieve.
SELECT * FROM Customers GROUPBY City HAVING City LIKE ‘Lo%’
DELETE STATEMENT:
To delete records from a table.
DELETE * FROM Customers WHERE City NOT IN(‘trichy’,’salem’)
UPDATE STATEMENT:
To update a database.
UPDATE Customers SET City=’trichy’ WHERE City=’tn’
JOINING TABLE:
SELECT Customers.ContactName,Orders.OrdersID FROM Customer ,Orders WHERE
Cutomers.CustomersID=Orders.CutomersID
WRITE SHORT NOTES ON AGGREGATE FUNCTION IN SQL.
SUM():
Return the tital of a column’s volues.
SELECT “total quality”=SUM(qty) FROM sales
MAX():
Return the maximum value for a column in a table or set of rows returned in aquery.
SELECT “Maximum Quantity”=MAX(qty) FROM sales
MIN():
Return the minimum value for a column in a table or set of rows returned in aquery.
SELECT “Minimum Quantity”=MIN(qty) FROM sales
AVG():
Calculate the average value of a column in a table or in a set of rows,depending on how it is used.
SELECT ”Average Quantity”=AVG(qty)FROM sales
COUNT():
Returns the count of rows in the query.
SELECT COUNT(*) FROM authors
CONVERT():
To ensure that you have the correct data types ti perform an operation.
SELECT title,royalty,”saless”=CONVERT(char(7),ytd_sales)FROM titles
GETDATA():
Return the current date and time from the server’s system clock.
SELECT GETDATE()
DITEDIFF():
Compare and return the difference between data items, such as days,weeks,minutes, and hours.
SELECT ord_date,”days difference”=DATEDIFF(dd,ord_date,GETDATE()) FROM sales
DITEPART():
Returns a value equals to the part of a date that you specify.
SELECT ord_date,”days of the week”=DATEPART(dw,ord_date)FROM sales
SUBSTRING():
Any string manipulation can be accomplished with this function in conjunction with a few string
operator and some other basic string function.
SELECT SUBSTRING(title,4,100) FROM Titles
LEFT() and RIGHT():
They are specially designed to work with the left or right end of the string you are manipulating.
SELECT LEFT(titles,20)FROM Titles
SELECT RIGHT(titles,20) FROM Titles
UPPER():
Converts the string passed to the function into all uppercase characters.
SELECT UPPER(au_fname) FROM authors
RTRIM and LTRIM:
RTRIM() removes any trailing blanks from a string or column.
LTRIM() works the same way as RTRIM() except that it removes blanks from the beginning
of a string instead of the end.
LEN():
To return the number of character of a given character string.
SELECT LEN(‘welcome’)
REPLICATE():
Return a character string which is repeated a specified number of times.
SELECT REPLICATE(‘-’,50)
SPACE():
Returns the specified number of spaces.
SELECT SPACE(10)+au_fname FROM authors
STR():
Converts a numeric value to character data.
SELECT STR(7238.26,6,1)
CHAR():
Returns the character that corresponds to the ASCII code passed as an integer to the function.
DROPPING A TABLE:
Sometimes you may not need a table during the transaction.
In such a case, you can drop or delete it directly from the ‘Server Explorer’.
To delete the user table, right-click on it and select the ‘Delete’ option from the context
menu.
Clicking on the ‘Delete’ option display a message box asking the user whether to
permanently delete the table from the database.
Click on the ‘Yes’ button if you want to delete the table permanently.
ASP.NET:
ASP.NET is a server side scripting technology that enables script (embedded in web pages)
to be executed by an Internet server.
There are many windows, controls and toolbars within the user interface.
When you start your program, a Start Page provides access to your recently created
applications and links to the MSDN support site, additional tools, and tutorials
available name on the start page to reopen the application quickly.
If you have closed the start page and want to reopen it, click View on the menu bar,
select other windows, and then click start page.
The properties window is used to set properties for objects, controls and classes.
The main window is used to view your project file.
The solution Explorer windows is used to manage all the files and resources within
your web applications.
The data explorer window is used to create and manage connections to database and
to manage data objects such as tables and stored procedures.
The Toolbox window contains frequency used control.
The following about the General and other tabs of the Toolbox:
Standard tab: Contains many of the Asp.net controls that are used within Asp.net pages.
Data tab: Provide access to data controls used to display data , and data source control.
Validation tab: Provides access to data controls used to validate web pages.
Navigation tab: Provides access to controls used to create site maps, menus and data sources.
Login tab: Provides access to controls that are used to create a login, password recovery and
change password forms, controls to view the visitor’s login status, and wizards to create users.
Web part tab: Provides access to create and manage a new way of organizing web parts and
web zones.
HTML tab: Provides access to the traditional HTML tags.
General tab: Does not contain any controls by default.
The dock able property to be moved to other locations on the desktop and to be
placed on top of one another.
Floating Property:
The floating property allows to select the windows and drag and drop it to any
locations on the desktop.
Server Control
ASP.NET provides a way to use server controls. These server controls are objects on the web
server built from classes that were installed when you installed .NET framework.
These server controls, such as HTML controls and ASP.NET controls, can be used only
within ASP.NET pages -that is, within pages that end in .aspx.
Important to understand that server controls will generate the output that is compatible with
the browser. Server controls can be configured to target a specific browser, or version of
HTML.
These server controls generate the necessary HTML tags, JavaScript, and dynamic HTML,
which are supported by the client.
Variables are store that can be retrieved at a later time. A variable declaration consists of
three parts: i. The declaration keywords ii. A variable name iii. Data type. The data type identifies
what kind of data the variable can store.
Declaring a variable:
Declaring a variable is the process of reserving the memory space for the variable before it is
used in the program.
Local variable are defined within a procedure and can be used only by the procedure in
which they were declared.
Module-level variables are defined in the class but outside of the procedures, and can be
used by any one of the procedures within the page.
The scope identifies what context of the application can access the variable.
Dim: with no other keyword, its use will mean the variable is public.
Public: This is used to declare a variable global or public, and therefore available to other
locations within same we page or form outside the web form.
Friend: This defines variables that are used only within the current web application or
project
Protected: This defines variables that can be used only by the procedure in which they were
declared.
Naming variables
You cannot use any one of the visual basic.NET commands or keywords as your variable
name.
Variable names must begin with a letter.
You cannot use a period or space within a variable name.
Avoid using any special characters in a variable name except for the underscore.
Declaring Constants
You can use a constant instead of a variable when you want o assign a value that does not
change. The Const keyword is used to declare a constant.
Example: Const TAXRATE As integer=8
HTTP is one of the protocols used to send and receive data over the Internet. The header is
the portion of a data packet that describes how and where to send the file. The user agent can be
used to identify the client software.
HTTP collects information and stores the values as collection server variables.
The Request object of the page class allows you to retrieve any data sent by the browser,
including the names and values of the form fields and the server variables.
Server variables can be retrieved by using an HTTP request object with Request .server
variables ("VARIABLE_NAME"). The server variable name is always in uppercase.
Session Objects
One of the biggest challenges in creating interactive web pages is maintaining the state of the
user.
User information can be tracked across user sessions and across the entire applications.
A special session cookie is used to maintain the session information.
Visual Basic .NET is used as the programming language for both types of applications.
ASP.NET is the technology used to develop dynamic web applications within the .NET framework.
The .NET framework consists of a common language runtime (CLR) and a hierarchical set of base
class libraries.
Both the logical and physical tires are related in an enterprise environment. The presentation
tier contains the user interface. The business programming logic, such as the formulas to calculate
interest rate, is implemented in components at a middle tier. It is useful to create the business
components to isolate the programming logic so that changes within the visual layer would not
impact the programming code. The data tier often consists of one or more data servers such as SQL
server. Making the application support a large number of visitors are called scaling. Scaling may
require adding more web servers to handle the requests, to deliver applications, and to store and
cache data. Scaling the application should not result in recording in well-designed application.
The calendercontrol is useful for allowing a user to select dates for plane,hotel,and
conference reservations.
It is used to display event data such as the location and timo of the event.
It is created by the calendar class .
The calendar control is System.Web.Controls.Calendar
Support properties,Methods,and Events:
The various calendar control properties that can be configured are follows
DayHeaderStyle:
Sets the style for the days of the weeks
Day style:
Sets the styles for the individual dates.
NextPrevStyle:
Sets the styles for the navigation controls in the heading.
OtherMonthDayStyle:
Sets the style for the dates that are not in current month
SeletedDayStyle:
Sets the style for the dates that are selected.
SeletorStyle:
Sets the style for the month date selection column.
TitleStyle:
Sets the style for the title in the heading.
TodayDayStyle:
Sets the style for the current date.
WeekEndDayStyle:
Sets the style for the weekend days.
Other properties that allow to modify the calender control’s appearance include the following:
ShowDayHeader property:
Show or hide the day’s of the week heading row.
ShowGridLines property:
Show or hide the gridlines that divide the days of month.
ShowNextPrev property:
Show or hide the navigation controls.
ShowTitle property:
Show or hide the title in the heading.
Using File Upload Control:
The file upload control allows you to upload a file to a web server. There are many
uses for a File Upload control, such as the following:
Online store, community and volunteer organizations, businesses.
4. in the parameter source drop-down list,select control.in the control ID drop-down list,selec
DropDownList as shown I fig 10-15.click next and then click finish.
5. Click the source tab. Locate the code for the price Bound Field column. Insert the
DataFormatString and HtmlEncode properties as shown in fig 10-16.
Using stored procedures with a FormView control
Create the stored procedures to select and update the database. In fig 10-23 displays the insert,
delete, and update parameters that have been inserted for you.
Securing Databases:
Securing databases
Detecting Database Errors
Securing Databases:
Hackers are people who intrude into another person’s software.
Their intensions may be to expose, modify or delete the data or files on your network.SQL
injection is a technique that is used by hackers to attach SQL statements to an existing SQL
query in order to run additional commands.
Detecting Database Errors:
Detecting database errors-The Exception object contains information about the error, such as
the exception umber which helps you determine the type of error that occurred.
.
Unit-V
Evolution of c#
The first release of C# (C# 1.0) was all about building a new language for managed code that
appealed, mostly, to C++ and Java programmers.
The second release (C# 2.0) was mostly about adding what wasn’t time to built into
the 1.0release. The main feature for this release was Generics.
The third release (C# 3.0) was all about reducing the impedance mismatch between general
purpose programming languages and databases. To achieve this goal, several functional
programming features were added to the language and LINQ was born.
High level language came in late 1950s with FORTRAN(formula translator) and later
COBOL(Common Business oriented language).
These language were considered as high level languages.because they were designed to the
accessible to humans - easy to read and write and close to English language.
Some of the more note worthy high level programming language are C,C++
vb,java & now c#.
C++ is an extension of c.which actually evolved from bcpl & bin 1973.
C was developrd by dennis Ritchie at bell lab.
Bjarne stroustrup is considered as the father of c++ for his design work in early 1980’s.
C++ includes features of oops c++ is used heavily in computer industry today.
Smalltask considered a pure ool was developed by Xerox palo alto research center(PARC).
Visual basic,introduced in 1991 deriverd from BASIC(Beginners all purpose symbolic
instruction code) programming language developed in 1960s.
VB easily creates the windows based graphical user interfaces(GUI)
Java was introduced in 1995 and was originally called oak.
Business community used for java most heavily for web applications.
C# is one of the newest programming language. It is closely to c and c++ but many
developers consider it akin to java
C# has GUI features of VB and added the power of C++ and object oriented class libraries
similar to java.
C# can be used to develop any type of software components including mobile applications,
dynamic web pages, databases access components, web services and console based
application .Net
.Net is an environment in which programs run and was designed to be a new programming
paradigm.
It is not an operating system but rather a buyer between operating system & other
application.
Officially announcement in 2000 .net was in development for over 3 years.
Finally in feb2002 microsoft finally released the first version of visual stdio,the the IDE for
developing c# .net ,vb .net,visual c++.net visual j# .net & visual c#.net
multilevel language Independent.
.Net framework baseclasses.
Dynamic web pages & web services->ADO.Net supports.
Going forward, new trends are showing up in the industry and modern programming languages need
to be more:
Declarative
With imperative languages, although having the eye on the what, programs need to focus on
the how.
This leads to over specification of the solution to the problem in hand, making next to
impossible to the execution engine to be smart about the execution of the program and
optimize it to run it more efficiently (given the hardware available, for example).
Declarative languages, on the other hand, focus only on the what and leave the howto the
execution engine.
LINQ made C# more declarative by using higher level constructs like orderby and group
by that give the execution engine a much better chance of optimizing the execution (by
parallelizing it, for example).
Concurrent
Concurrency is hard and needs to be thought about and it’s very hard to shoehorn it into a
programming language. Parallel.For (from the parallel extensions) looks like a
parallel for because enough expressiveness has been built into C# 3.0 to allow this without
having to commit to specific language syntax.
Dynamic
There was been lots of debate on which ones are the better programming
languages: static or dynamic.
The fact is that both have good qualities and users of both types of languages want to have
it all.
All these trends require a paradigm switch. C# is, in many ways, already a multi-paradigm
language.
It’s still very object oriented (class oriented as some might say) but it can be argued that C#
3.0 has become a functional programming language because it has all the cornerstones of
what a functional programming language needs. Moving forward, it will have even more.
Besides the influence of these trends, there was a decision of co-evolution of
the C# and Visual Basic programming languages.
Since its inception, there has been some effort to position C# and Visual Basic against each
other and to try to explain what should be done with each language or what kind of
programmers use one or the other.
Each language should be chosen based on past experience and familiarity of the
developer/team/project/company and not by particular features.
In the past, every time a feature was added to one language, the users of the other wanted
that feature too.
Going forward, when a feature is added to one language, the other will work hard to add the
same feature.
This doesn’t mean that XML literals will be added to C# (because almost the same can be
achieved with LINQ To XML), but Visual Basicwill have auto-implemented properties.
Most of these features require or are built on top of features of the .NET Framework and, the
focus for C# 4.0 was on dynamic programming, not just dynamic types but being able to talk
with anything that isn’t a .NET class.
Also introduced in C# 4.0 is co-variance and contra-variance for
generic interfaces and delegates.
C# Relates to .NET Framework
C# has a special relationship to its runtime environment,the .NET Framework.
The reason for this is twofold.
o C# was initially designed by Microsoft to create code for the .NET Framework.
o The libraries used by C# are the ones defined by the .NET Framework.
WHY C#
C#,Pronounced c sharp,is a computer language used to give instructions that tell the
computer what to do,how to do it,and when to do it.
The Microsoft .NET Framework is a library of objects that create or draw things on the
computer.
The C# language is used to create applications that display on a black window referred to
as the DOS prompt or DOS window.
ELEMENTS OF C# PROGRAM
There are basic elements that all C# executable programs with a simple c# program.
Comments
Using Directive
Namespace
Class definition
Main Method
Comments:
Writing comment is like making notes for yourself or for readers of your program.
Comments are not considered as a instruction to the computer.
Eg:
//This is first program
This 2 forward slashes used to indicate comment a single line.
Comments serve 2 functions
*They make the code more readable.
*They internally,document,what the program statement are doing.
In c#, there are 3 types of commenting syntax
1.Inline comments
2.Multiline comments
3.XML Document comments
1. Inline comments:
\\ first program
*Single line comment is said to be Inline comment.
*An Inline comments is indicated by two forward slashes. It is ignored by the compiler.
2. Multiline comments:
*Used for longer comments.
*A forward slash followed by an asterisk /* marks the beginning of a multiline comment and */
marks at the end.
Eg:
/* This is first line at the end of the program */
XML Document comment
*Uses 3 forward slashes///
*This is advanced documentation technique used for xml style comments.
Using Directive
Used to permits the use of classes found in particular namespace.
Eg:
Using system;
Where “system” is a namespace.
.Net provides more then 2000 classes that make up FCL.Used to reuse the code.
Eg:
Using system.console;
Most frequently used namespace is system
Console.writeline(“Hellow world”)
(or)
NameSpace
Namespace firstprogram
{
Stmts;
}
Class definition
C# Language,so everything is designed around a class,which is a building block of oop.
Eg:
Static void main()
{
Console.write(“Hellow”);
Console.write(“ “);
Console.write(“world!”);
)
o/p:
Hellow world!
*Here Main() is call another method name “write”
*A Method call is the same as Method invocation.Like main(),writeline() has a signature.
*The heading along with the body of the method is the definition on the Method.
Escape sequence:
/n -> next line
/t ->horizontal tab
/” -> double quotes
/’ -> single quotes
// ->Back slash
PROGRAMMING EXAMPLE
[C#]
Public static boolIsLocallpAddress(string host)
{
Try
{// get host IP addresses
IP Address[] hostIPs=Dns.GetHostAddresses(Dns.GetHostName());
//test if any host IP equals to any local IP or to localhost
Foreach(IPAddresshostIP in hostIPs)
{
//is localhost
If(IPAddress.IsLoopback(hostIP)) return true;
//is local address
Foreach(IP Address localIP in localIPs
{
If(hostIP.Equals(localIP)) return true;
}
}
}
Catch{}
Return false;
}
Syntax:
DataType VariableName
DataType: The type of data that the variable can hold
VariableName: The variable we declare for hold the values.
EXAMPLE:
Int count;
Int:is the data type
Count: is the variable name
BOOL
It is used to declare variable to store the Boolean values, true and false.
In C#, there is no conversion between the bool type and other types.
MAKKING DECISION
The familiar if-then of visual basic,pascal and fortran has its analog in c#
if(y>0)
Z=x/y;
Paranthesis around the condition are required in c#.if you want to have several statements as part
of the condition.you must enclose them in braces:
If(y>0)
{
z=x/y;
Console.riteline(“z=”+z);
}
If you want to carry out either one set of statements or another depending on a single
condition,you should use the else clause along with the if statement.
If (y>0)
Z=x/y;
Else
Z=0;
And if the else clause contains multiple statements,they must be enclosed in braces,as in the
code above.there are two types of styles for braces:
If(y>0)
{
Z=x/y;
}
The other style, the if statement and the ending brace directly under the if:
If(y>0)
{
Z=x/y;
Console.writeline(“z=”+z);
}
Using system;
if(number>10)
console.writeline(“hey! The number should be 10 or less!”);
else
if(number<0)
console.writeline(“hey! The number should be 0 or more!”);
else
console.writeline(Good job!”);
console.Readline();
}
}
}
Comparison Operators
Above, we used the > operator to mean “greater than.” Most of these operators are the same in
C# as they are in C and other languages.
Note particularly that “is equal to” requires two equal signs and that “not equal” is different than
in FORTRAN or VB.
Combining Conditions
When you need to combine two or more conditions in a single if or other logical statement,
you use the symbols for the logical and, or, and not operators. These are totally different than
any other languages except C/C++ and are confusingly like the bitwise operators shown in
Table 2.
syntax
Switch(expression)
{
Case value1:stmt;
Break;
Case value2:stmt;
Break;
Case value n:stmt;
Break;
Default: stmt;
Break;
}
Eg:
Switch(weekday)
{
Case 1: console.writeline(“Mon”);
Break:
Case 2:Console.writeline(“tue”);
Break;
Case 3: console.writeliine(“wed”);
Break;
}
REPEATING INSTRUCTIONS
WHILE STATEMENT
FOR STATEMENT
SWITCH STATEMENT
DO/WHILE STATEMENT
While Statement
A repetition structure allows the programmer to specify that an action is to be repeated while
a condition remains true.
Syntax:
while (expression) statement
Example
Int product =2;
While(product<=1000)
Product =2* product;
For Statement
The for repetition structure handles the details of counter-controlled repetition.
Syntax:
for(initialization; condition; step)
statement
Example
Using System;
Class ForCounter
{
Static void Main(string[]args)
{
for(int counter=1;counter<=5;counter++)
Console.WriteLine(counter);
}
}
Switch Multiple-Selection Structure
C# provides the switch multiple-selection structure to handle such decision making.
Syntax:
switch (expression)
{
case constant-expression:
statement(s);
jump-statement
[default: statement(s);]
Example
switch(grade)
{
case’A’:
case’a’:
++aCount ;
Break;
case’B’:
case’b’:
++bCount ;
Break;
default:
Console.Writeln(“Incorrect letter grade entered,”+”\nGrade not added to totals.”);
Break;
}
Do/While Statement
The do/while structure tests the loop-continuation condition after the loop body
executes.Therefore,the loop body always excutes at least once.
When a do/while structure terminates,execution continues with the statement after the while
cause.
Syntax:
Do
{
Statements
} while (condition);
Example
Using System;
Class MainClass
{
Public static void main()
{
int n=0;
do
{
Console.WriteLine(“Number is {0}”,n);
n++;
}
While (n<10);
}
}
}
Output:
Number is 0
Number is 1
Number is 2
Number is 3
Number is 4
Number is 5
Number is 6
Number is 7
Number is 8
Number is 9
Number is 10
ARRAYS:-
Another detail is that the size of the array is not part of its type as it is in the C
language.
This allows you to declare an array and assign any array of int objects to it, regardless
of the array's length.
DECLARING ARRAYS:-
SINGLE-DIMENSIONAL ARRAYS:
int[] numbers;
MULTIDIMENSIONAL ARRAYS:
string[,] names;
ARRAY-OF-ARRAYS (JAGGED):
byte[][] scores;
Declaring them (as shown above) does not actually create the arrays.
In C#, arrays are objects (discussed later in this tutorial) and must be instantiated.
The following examples show how to create arrays:
SINGLE-DIMENSIONAL ARRAYS:
MULTIDIMENSIONAL ARRAYS:
ARRAY-OF-ARRAYS (JAGGED):
You can also have larger arrays. For example, you can have a three-dimensional rectangular
array:
You can even mix rectangular and jagged arrays. For example, the following code declares a
single-dimensional array of three-dimensional arrays of two-dimensional arrays of type int:
int[][,,][,] numbers;
Example
The following is a complete C# program that declares and instantiates arrays as discussed above.
// arrays.cs
using System;
classDeclareArraysSample
{
public static void Main()
{
// Single-dimensional array
int[] numbers = new int[5];
// Multidimensional array
string[,] names = new string[5,4];
Output
Copy
Length of row 0 is 3
Length of row 1 is 4
Length of row 2 is 5
Length of row 3 is 6
Length of row 4 is 7
INITIALIZING ARRAYS:-
Note : If you do not initialize an array at the time of declaration, the array members are
automatically initialized to the default initial value for the array type. Also, if you declare the array
as a field of a type, it will be set to the default value null when you instantiate the type.
SINGLE-DIMENSIONAL ARRAY:-
You can also omit the newoperator if an initializer is provided, like this:
MULTIDIMENSIONAL ARRAY:-
You can also omit the newoperator if an initializer is provided, like this:
int[][] numbers = new int[2][] { new int[] {2,3,4}, new int[] {5,6,7,8,9} };
You can also omit the size of the first array, like this:
int[][] numbers = new int[][] { new int[] {2,3,4}, new int[] {5,6,7,8,9} };
-or-
Notice that there is no initialization syntax for the elements of a jagged array.
Accessing array members is straightforward and similar to how you access array
members in C/C++.
For example, the following code creates an array called numbers and then assigns a 5
to the fifth element of the array:
The following code declares a multidimensional array and assigns 5 to the member
located at [1, 1]:
int[,] numbers = { {1, 2}, {3, 4}, {5, 6}, {7, 8}, {9, 10} };
numbers[1, 1] = 5;
int[][] numbers = new int[][] { new int[] {1, 2}, new int[] {3, 4, 5} };
The following statements assign 58 to the first element of the first array and 667 to the
second element of the second array:
numbers[0][0] = 58;
numbers[1][1] = 667;
With multidimensional arrays, you can use the same method to iterate through the
elements, for example:
int[,] numbers = new int[3, 2] {{9, 99}, {3, 33}, {5, 55}};
foreach(int i in numbers)
{
Console.Write("{0} ", i);
}
The output of this example is:
9 99 3 33 5 55
However, with multidimensional arrays, using a nested for loop gives you more control over the
array elements
COLLECTIONS:-
ARRAYLIST:-
ArrayList is one of the most flexible data structure from CSharp Collections.
ArrayList contains a simple list of values
ArrayList implements the IList interface using an array and very easily we can add ,
insert , delete , view etc.
It is very flexible because we can add without any size information , that is it will grow
dynamically and also shrink .
Syntax :
ArrayList.add(object)
object : The Item to be add the ArrayList
ArrayListarr;
Eg: arr.Add("Item1");
Syntax :
ArrayList.insert(index,object)
index : The position of the item in an ArrayList
object : The Item to be add the ArrayList
ArrayListarr;
Syntax :
ArrayList.Remove(object)
object : The Item to be add the ArrayList
Eg: arr.Remove("item2")
Syntax :
ArrayList.RemoveAt(index)
index : the position of an item to remove from an ArrayList
Eg: ItemList.RemoveAt(2)
sortArrayList
Syntax : ArrayList.Sort()
Eg program:-
using System;
usingSystem.Collections;
usingSystem.Windows.Forms;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int i = 0;
ArrayListItemList = new ArrayList();
ItemList.Add("Item4");
ItemList.Add("Item5");
ItemList.Add("Item2");
ItemList.Add("Item1");
ItemList.Add("Item3");
MessageBox.Show ("Shows Added Items");
for (i = 0; i < = ItemList.Count - 1; i++)
{
MessageBox.Show(ItemList[i].ToString());
}
//insert an item
ItemList.Insert(3, "Item6");
//sort itemms in an arraylist
ItemList.Sort();
//remove an item
ItemList.Remove("Item1");
//remove item from a specified index
ItemList.RemoveAt(3);
MessageBox.Show("Shows final Items the ArrayList");
for (i = 0; i < = ItemList.Count - 1; i++)
{
MessageBox.Show(ItemList[i].ToString());
}
}
}
}
when you execute this C# program , at first add five items in the arraylist and displays.
Then again one more item inserted in the third position , and then sort all items.
Next it remove the item1 and also remove the item in the third position . Finally it shows the
existing items.
HASHTABLE:-
In C# represents a collection of key/value pairs which maps keys to value.
Any non-null object can be used as a key but a value can.
We can retrieve items from hashTable to provide the key .
Both keys and values are Objects.
The commonly used functions in Hashtable are :
Syntax : HashTable.Add(Key,Value)
Key : The Key value
Value : The value of corresponding key
Hashtableht;
ht.Add("1", "Sunday");
Synatx : boolHashTable.ContainsKey(key)
Key : The Key value for search in HahTable
Returns : return true if item exist else false
ht.Contains("1");
Synatx : boolHashTable.ContainsValue(Value)
Value : Search the specified Value in HashTable
Returns : return true if item exist else false
ht.ContainsValue("Sunday")
ht.Remove("1");
using System;
usingSystem.Collections;
usingSystem.Windows.Forms;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Events provide a generally useful way for object to signal state changes that may be useful to
clients of that objects.
Events are an important building block for creating classes that can be reused in large
number of different programs.
An event is a way for a class to allow clients to give it delegates to methods that should be
called when the event occurs.
When the event occurs, the delegates given to it by its clients are invoked.
New :
{
richTextBox1.Text = "";
}
Open :
-------
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
richTextBox1.LoadFile(openFileDialog1.FileName,
RichTextBoxStreamType.PlainText);
}
}
Save : -
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
richTextBox1.SaveFile(saveFileDialog1.FileName ,
RichTextBoxStreamType.PlainText);
}
}
Exit :
------
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Close();
}
Cut :
-----
private void cutToolStripMenuItem_Click(object sender, EventArgs e)
{
richTextBox1.Cut();
}
Copy :
--------
private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
richTextBox1.Copy();
}
Paste : --------
richTextBox1.SelectAll();
}
Font : -------
Open:-
--------
private void toolStripButton2_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
richTextBox1.LoadFile(openFileDialog1.FileName,
RichTextBoxStreamType.PlainText);
}
toolStripStatusLabel1.Text = "file opened";
}
Paste:-
---------
private void toolStripButton3_Click(object sender, EventArgs e)
{
richTextBox1.Paste();
}
Save:-
-------
private void toolStripButton4_Click(object sender, EventArgs e)
{
saveFileDialog1.Filter = "Textfile|*.txt|All Files|*.*";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
richTextBox1.SaveFile(saveFileDialog1.FileName,
RichTextBoxStreamType.PlainText);
}
toolStripStatusLabel1.Text = "File Saved";
}
Copy:-
--------
private void toolStripButton6_Click(object sender, EventArgs e)
{
richTextBox1.Copy();
}
Copy:-
---------
private void toolStripButton5_Click(object sender, EventArgs e)
{
richTextBox1.Cut();
}
}
}
Menus Output:-
New:
Open :
Save :
Cut :
DATABASE ACCESS WITH ADO.NET
ADO.NET is a set of classes that expose data access services to the .NET programmer.
ADO.NET provides a rich set of components for creating distributed, data-sharing
applications.
It is an integral part of the .NET Framework, providing access to relational data, XML, and
application data. ADO.NET supports a variety of development needs, including the
creation of front-end database clients and middle-tier business objects used by
applications, tools, languages, or Internet browsers.
To Use the ADO classes we need to include the ADO.NET namespace and a few handy date
classes.
ADO.NET provides consistent access to data sources such as Microsoft SQL Server, as well
as data sources exposed through OLE DB and XML.
Data-sharing consumer applications can use ADO.NET to connect to these data sources and
retrieve, manipulate, and update data.
The ADO.NET classes are found in System.Data.dll, and are integrated with the XML
classes found in System.Xml.dll. When compiling code that uses
the System.Data namespace, reference both System.Data.dll and System.Xml.dll. For an
example of compiling an ADO.NET application using a command line compiler,
see ADO.NET Sample Application.
ADO.NET provides functionality to developers writing managed code similar to the
functionality provided to native COM developers by ADO.
ADO.NET provides data access services in the Microsoft .NET platform.
You can use ADO.NET to access data by using the new .NET Framework data providers which are:
There are two central components of ADO.NET classes: the DataSet, and
the .NET Framework Data Provider.
UsingSystem.Data;
usingSystem.data;ADO
usingSystem.globalization;
publicconst string DB_CONN_STRING=“Driver={Mocrosoft Access Driver(*.mdb)};”+
“DBQ=D:\\CS\\TrstDbReadWrite\\SimpleTest.mdb”;
Reading data
Reading is done using the ADODataReaderclass.the steps to perform the read are;
ADODataReaderdr;
ADOCommandcmd=new ADOCommend(“SELECT*FROM person”,conn);
Cmd.Execute(out dr);
We loop through each record in the ADODataReader until we are done.
While(dr.Read() )
{
System.console.WriteLine(dr[“firstName”]);
}
Insert,Modify,Delete and other SQL commands
Inserting,Modifying and Deleting can very simply be done using SQL statements.the
following code performs a SQL commend to insert a record.
Be sure the strings do not include any embedded single or double quotes.
Modifying
The UPDATE command indicates the records to be modified and the modification to be
made.
The return value of the ExecuteNonQuery() indicates the number of records changes.