Saturday, July 23, 2011

Owned Forms, InputBox

Owned Forms
Visual Basic also allows us to create owned forms. An owned form is tied to the form that owns it. If you minimize the owner form, the owned form will also be minimized, if you close the owner form, the owned form will be closed and so on. Owned Forms are added to a form with the AddOwnedForm method and removed with the RemoveOwnedForm method. The following code demonstrates the creation of owned forms. Drag a Button from the toolbox onto the form (form1). When you click the button, Form1 will make an object of the Form class into an owned form and displays it. The code for that looks like this:


Public Class Form1 Inherits System.Windows.Forms.Form
Dim OwnedForm1 As New Form()

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e_
As System.EventArgs) Handles Button2.Click
Me.AddOwnedForm(OwnedForm1)
'adding an owned form to the current form
OwnedForm1.show()
'displaying the owned form
End Sub


The image below displays output from above code.

Owned Form
InputBox Function 
InputBox function gets a string of text entered by the user. They are similar to the JavaScript prompt windows that ask us to enter some text and performs some action after the OK button is clicked. In Visual Basic Input boxes let you display a prompt, read the text entered by the user and returns a string result. The following code demonstrates InputBox function. Drag a Button and TextBox control from the toolbox onto the form. When you click the Button, InputBox asks to enter some text and after you click OK it displays the text you entered in the TextBox. The image below displays output.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e_
As System.EventArgs) Handles Button1.Click
Dim s As String = InputBox("Enter some text")
'storing the text entered in a string
TextBox1.Text = s
'displaying string in the textbox
End Sub


Working with Forms (Continued)

Adding a New Form to the Project
You can add a new form to the project with which you are working. To do that,  select File->Add New Item from the main menu which displays a window asking you what to add to the project. Select Windows Form from the window and click Open to add a new form to the project. Alternatively, you can add a new form with the Solution Explorer. To add a new form with the Solution Explorer, right-click on the project name in Solution Explorer and Select Add->Add Windows Form. Once you finish adding a new form, if you want the form which you added to be displayed when you run the application you need to make some changes. You need to set the new form as Startup Object. To do that,  right-click on the project name in Solution Explorer window and select Properties which displays the Property Pages window. On this window click the drop-down box which is labeled as Startup Object. Doing that displays all the forms available in the project. It looks like the image below.

Property Pages Window
Select the form which you want to be displayed when you run the application and click Apply. Now, when you run the application, the form you assigned as Startup object will be displayed.
Working with Multiple Forms
Let's see how we can work with more than one form/open a new form. Say, for example, we want to open a new form (Form2) when a button in the current form (Form1) is clicked. To do that, open a new project by selecting File->New->Project->Visual Basic->WindowsApplication. This adds a form (Form1) to the application. Add a new form (Form2) by selecting File->Add New Item->Windows Form. Also, drag a button (Button1) onto Form1. We want to open Form2 when the button in Form1 is clicked. Unlike earlier versions of Visual Basic, VB .NET requires us to refer to Form2 in Form1 in order to open it i.e creating an object of Form2 in Form1. The code for that looks like this:

Public Class Form1 Inherits System.Windows.Forms.Form
Dim other As New Form2()
'Creating a reference to Form2
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles Button1.Click
other.Show()
End Sub

Visual Inheritance with Forms
As we know, Inheritance allows us to derive one class from another. VB. NET allows us to inherit one form from another. Let's see how we can inherit a new form from an existing form. Say, we have a form named Form1 with some controls on it and we want to inherit a new form from that form. To derive a new form from the existing one select Project->Add Inherited Form from the main menu. Doing that opens the Add New Item window. Double-click on the Inherited Form Icon in the templates box to open the Inheritance Picker. Inheritance Picker window looks like the image below.

Inheritance Picker Window
Select Form1 in the picker and click OK. Clicking OK adds a new form, Form2, which is derived from Form1. Everything on Form2 including the title is copied from Form1. The only difference between form1 and form2 is, the controls on Form2 come with a special icon at the upper left corner which indicates that the form is inherited and the controls are locked. The image below displays a Inherited Form.


Inheriting a Form from Other Project
You can also inherit a form from other project. To inherit a form from other project, navigate to the project containing the form you want using the browse button in the Inheritance Picker dialog, click the name of the DLL file containing the form and click Open. This returns to the inheritance Picker dialog box where the selected project is now listed. Choose the appropriate form and click OK. A new inherited form is added to your project.

Working with Forms

Well, let's now start working with Forms. When you open a new form you can have a look at the default properties of the form by selecting View->Properties Window or by pressing F4 on the keyboard. The properties window opens with default properties set to form by the software.
Briefly on Properties (Categorized):
Appearance
Appearance section of the properties window allow us to make changes to the appearance of the form. With the help of appearance properties we can have a background color, background image for the entire form, set the border style for the form from a predefined list, change the cursor, set the font for the text on the form and so on.
Behavior
Notable Behavior property is the enabled property which lets us enable/disable the form by setting the property to True/False.
Layout
Layout properties are all about the structure of the form. With these properties we can set the location of the form, maximum size of the form, minimum size of the form, exact size of the form with the size property when designing. Note the property start position, this property lets you specify the location of the form where it should appear when you run the application which you can select from a predefined list.
Window Style
The notable property under this is the ControlBox property which by default it is set to True. Setting the property to False makes the minimize, maximize and cancel buttons on the top right side of the form invisible.
Form Event
The default event of a form is the load event which looks like this in code:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)_
Handles MyBase.Load

End Sub

You can write code in the load event of the form just like you write for all other controls.
An Example:
You can run the Form by selecting Debug->Start from the main menu or by pressing F5 on the keyboard. When you run a blank form with no controls on it, nothing is displayed. It looks like the image below.

Blank Form
Now, add a TextBox and a Button to the form from the toolbox. The toolbox can be selected from
View->ToolBox on the main menu or by holding Ctrl+Alt+X on the keyboard. Once adding the TextBox and Button is done, run the form. The output window displays a TextBox and a Button. When you click the Button nothing happens. We need to write an event for the Button stating something should happen when you click it. To do that get back to design view and double-click on the  Button. Doing that opens an event handler for the Button where you specify what should happen when you click the button. That looks like this in code.

Public Class Form1
Inherits System.Windows.Forms.Form
#Region " Windows Form Designer generated code "
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)_
Handles MyBase.Load
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles Button1.Click
End Sub
End Class

Place the code TextBox1.Text="Welcome to Forms" in the Click event of the Button and run the application. When you click the Button the output "Welcome to Forms" is displayed in the TextBox.
Alternatively, you can also use the MsgBox or MessageBox functions to display text when you click on the Button. To do that place a Button on the form and double-click on that to open it's event. Write this line of code, MsgBox("Welcome to Forms") or MessageBox.Show("Welcome to Forms").

It looks like this in code.


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles Button1.Click
MsgBox("Welcome to Forms")
End Sub

or

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles Button1.Click
MessageBox.Show("Welcome to Forms")
End Sub

When you run the form and click the Button, a small message box displays, "Welcome to Forms". The image below displays that.

Windows Form Properties

Below are the properties of a Windows Form. Properties displayed below are categorized as seen in the properties window.
Appearance PropertiesDescription
BackColorGets/Sets the background color for the form
BackgroundImageGet/Sets the background image in the form
CursorGets/Sets the cursor to be displayed when the user moves the mouse over the form
FontGets/Sets the font for the form
ForeColorGets/Sets the foreground color of the form
FormBorderStyleGets/Sets the border style of the form
RightToLeftGets/Sets the value indicating if the alignment of the control's elements is reversed to support right-to-left fonts
TextGets/Sets the text associated with this form
Behavior PropertiesDescription
AllowDropIndicates if the form can accept data that the user drags and drops into it
ContextMenuGets/Sets the shortcut menu for the form
EnabledGets/Sets a value indicating if the form is enabled
ImeModeGets/Sets the state of an Input Method Editor
Data PropertiesDescription
DataBindingsGets the data bindings for a control
TagGets/Sets an object that contains data about a control
Design PropertiesDescription
NameGets/Sets name for the form
DrawGridIndicates whether or not to draw the positioning grid
GridSizeDetermines the size of the positioning grid
LockedGets/Sets whether the form is locked
SnapToGridIndicates if the controls should snap to the positioning grid
Layout PropertiesDescription
AutoScaleIndicates if the form adjusts its size to fit the height of the font used on the form and scales its controls
AutoScrollIndicates if the form implements autoscrolling
AutoScrollMarginThe margin around controls during auto scroll
AutoScrollMinSizeThe minimum logical size for the auto scroll region
DockPaddingDetermines the size of the border for docked controls
LocationGets/Sets the co-ordinates of the upper-left corner of the form
MaximumSizeThe maximum size the form can be resized to
MinimumSizeThe minimum size the form can be resized to
SizeGets/Sets size of the form in pixels
StartPositionGets/Sets the starting position of the form at run time
WindowStateGets/Sets the form's window state
Misc PropertiesDescription
AcceptButtonGets/Sets the button on the form that is pressed when the user uses the enter key
CancelButtonIndicates the button control that is pressed when the user presses the ESC key
KeyPreviewDetermines whether keyboard controls on the form are registered with the form
LanguageIndicates the current localizable language
LocalizableDetermines if localizable code will be generated for this object
Window Style PropertiesDescription
ControlBoxGets/Sets a value indicating if a control box is displayed
HelpButtonDetermines whether a form has a help button on the caption bar
IconGets/Sets the icon for the form
IsMdiContainerGets/Sets a value indicating if the form is a container for MDI child forms
MaximizeBoxGets/Sets a value indicating if the maximize button is displayed in the caption bar of the form
MenuGets/Sets the MainMenu that is displayed in the form
MinimizeBoxGets/Sets a value indicating if the minimize button is displayed in the caption bar of the form
OpacityDetermines how opaque or transparent the form is
ShowInTaskbarGets/Sets a value indicating if the form is displayed in the Windows taskbar
SizeGripStyleDetermines when the size grip will be displayed for the form
TopMostGets/Sets a value indicating if the form should be displayed as the topmost form of the application
TransparencyKeyA color which will appear transparent when painted on the form

Windows Forms

In Visual Basic its these Forms with which we work. They are the base on which we build, develop all our user interface and they come with a rich set of classes. Forms allow us to work visually with controls and other items from the toolbox. In VB .NET forms are based on the System.Windows.Forms namespace and the form class is System.Windows.Forms.Form. The form class is based on the Control class which allows it to share many properties and methods with other controls. When we open a new project in Visual Basic the dialogue box that appears first is the one which looks like the image below. Since we are working with Windows Applications (Forms) you need to select WindowsApplication and click OK.


Once you click OK a new Form opens with the title, Form1, towards the  top-left side of the form and maximize, minimize and close buttons towards the top right of the form. The whole form is surrounded with a border. The main area of the form in which we work is called the Client Area. It's in this client area we design the user interface leaving all the code to the code behind file. Forms also support events which let's the form know that something happened with the form, for example, when we double-click on the form, the Form load event occurs. VB .NET also supports forms to be inherited.
Image of a Windows Form.


Typically the Form looks like this in Code which is handled by the Framework.
Public Class Form1
Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

Public Sub New()
MyBase.New()

'This call is required by the Windows Form Designer.
InitializeComponent()

'Add any initialization after the InitializeComponent() call

End Sub

'Form overrides dispose to clean up the component list.
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If Not (components Is Nothing) Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub

'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer

'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
'
'Form1
'
Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
Me.ClientSize = New System.Drawing.Size(496, 493)
Me.Name = "Form1"
Me.Text = "Form1"

End Sub

#End Region

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

End Sub
End Class

Wednesday, July 20, 2011

Shortcut Keys


KeyWhat it Does?
Ctrl + NOpens the New Project Dialogue Box
Ctrl + Shift + OOpens the Open File Dialog Box
Ctrl + Shift + AOpens Add New Item window
Ctrl + DOpens Add Existing Item window
Ctrl + S Saves Current Form
Ctrl + Shift + S Saves everything from Application
Alt + QExits Visual Studio. NET
Ctrl + ZUndo
Ctrl + Shift + ZRedo
Ctrl + XCuts your selection
Ctrl + CCopies your selection
Ctrl + VPastes your selection
Ctrl + ASelects All
DelDeletes your selection
Ctrl + FOpens Find window
Ctrl + HOpens Find and Replace window
Ctrl + Shift + HOpens Replace in Files window
Ctrl + Alt + Shift + F12Opens Find Symbol window
F7Opens Code Designer window
Shift + F7Gets you back to Design View
Ctrl + ROpens the Solution Explorer window
Ctrl + Alt + SOpens the Server Explorer window
Ctrl + Shift + COpens the Class View window
F4Opens the Properties window
Ctrl + Shift + EOpens the Resource view window
Ctrl + Alt + XOpens the Toolbar window
Shift + Alt + EnterTakes you to Full Screen View
Alt+F8Opens Macro Explorer window
F2Opens Object Browser window
Ctrl + Alt + TOpens Document Outline window
Ctrl + Alt + KOpens Task List window
Ctrl + Alt + AOpens Command window
Ctrl + Alt + OOpens Output window
Ctrl + Alt + YOpens Find Symbol Results window
Ctrl + Alt + FLists Items under the Favorites Menu in your Internet Explorer
Ctrl + Shift + BBuilds your project
F5Runs your Application
Ctrl + F5Runs your Application without Debugging
Ctrl + Alt + EOpens the Exceptions Dialog Box
F8Used while Debugging Applications
Shift + F8Used While Debugging Applications
Ctrl + BInserts a New Breakpoint
Ctrl + Shift + F9Clears All Breakpoints
Ctrl + Alt + POpens the Processes Dialog box
Ctrl + TOpens Customize Toolbox window
Ctrl + Shift + PRuns Temporary Macro
Ctrl + Shift + RRecords Temporary Macro
Alt + F11Opens Macros IDE
Ctrl + F1Opens Dynamic Help window
Ctrl +Alt + F1Opens Help window sorted by Contents
Ctrl + Alt + F2Opens Help window sorted by Index
Ctrl + Alt + F3Opens Help Search window
Shift + Alt + F2Opens Index Results window
Shift + Alt + F3Opens Search Results window

Visual Studio .NET IDE

Visual Studio .NET IDE (Integrated Development Environment) is the Development Environment for all .NET based applications which comes with rich features. VS .NET IDE provides many options and is packed with many features that simplify application development by handling the complexities. Visual Studio .NET IDE is an enhancement to all previous IDE’s by Microsoft.
Important Features 
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.
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.
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.
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.

StartPage
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.

IDE
New Project Dialogue Box
The New Project dialogue box like the one in the image below is used to create a new project specifying it's type allowing us to name the project and also specify it's location on the disk where it is saved. The default location on the hard disk where all the projects are saved is C:\DocumentsandSettings\Administrator\MyDocuments\VisualStudioProjects.

New Project Dialogue
Following are different templates under Project Types and their use.
Windows Application: This template allows to create standard windows based applications.
Class Library: Class libraries are those that provide functionality similar to Active X and DLL by creating classes that access other applications.
Windows Control Library: This allows to create 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.
ASP .NET Web Application: This allows to create web-based applications using IIS. We can create web pages, rich web applications and web services.
ASP .NET Web Service: Allows to create XML Web Services.
Web Control Library: Allows to create User-defined controls for the Web. Similar to user defined windows controls but these are used for Web.
Console Application: A new kind of application in Visual Studio .NET. They are command line based applications.
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.
Other: This template is to develop other kinds of applications like enterprise applications, database applications etc.
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.

Solution Explorer Window
Server Explorer Window
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.

Server Explorer Window
Intellisense
Intellisense 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.

Intellisense
Code Designer Window
Code Designers like the image below allows us to edit and write code. This is the window that opens when we double-click on a form or any control. This is the place where we write all the code for the application. Notice the two drop-down list boxes at the top of the code window in the image below. The left box allows us to select the object's code we are working with and the right box allows us to select the part of code that we want to work. Also notice the "+" and "-" boxes in the code designer. You can use those boxes to display code Visual Basic .NET already created, like, Windows Forms Designer generated code, etc.

Code Designer Window
Properties Window
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, backcolor, 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.

Properties Window
Dynamic Help Window
The dynamic help window displays help which looks up for things automatically. For example, if you want to get help with a form, select the form and select Help->Dynamic Help from the main menu. Doing that displays all the information relating to forms. The image below displays that. You can get help relating to anything with this feature. Say, if you want to know more about the form, select the form and select Dynamic Help from the Help menu. Doing that displays information about the form as shown in the image below..

Dynamic Help Window

Command Window
The command window in the image below is a useful window. Using this window we can add new item to the project, add new project and so on. You can view the command window by selecting
View->Other Windows->Command Window from the main menu. The command window in the image displays all possible commands with File.

Command Window
Task List Window
The task list window displays all the tasks that VB .NET assumes we still have to finish. You can view the task list window by selecting View->Show tasks->All or View->Other Windows->Task List from the main menu. The image below shows that. As you can see from the image, the task list displayed "TextBox1 not declared", "RichTextBox1 not declared". The reason for that message is, there were no controls on the form and attempts where made to write code for a textbox and a richtextbox. Task list also displays syntax errors and other errors you normally encounter during coding

TaskList Window
Class View Window
The class view window like the image below is the window that presents solutions and projects in terms of the classes they contain and the members of these classes. Using the class view window also helps us to find a member of a class that we want to work with. As you can notice from the image, the class view window displayed all the methods and events for the controls which were available on the form.

Class View Window
Output Window
The output window as you can see in the image below displays the results of building and running applications.

Output Window
Object Explorer Window
The object explorer window allows us to view all the members of an object at once. It lists all the objects in our code and gives us access to them. The image below displays an object explorer window. You can view the object explorer window by selecting View->Other Windows-> Object Browser from the main menu.

Object Explorer Window
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.

Toolbox Window

Strings, Math Functions

Strings
Strings in Visual Basic are supported by the .NET String class. The String data type can represent a series of characters and can contain approximately up to 2 billion Unicode characters. There are many built-in functions in the String class. Some .NET Framework functions are also built into the String class. The following code puts some String functions to work.

Imports System.Console
Module Module1

Sub Main()
Dim string1 As String = "Strings in Visual Basic"
Dim string2 As String
Dim string3 As String
Dim string4 As String
Dim string5 As String
Dim string6 As String
string2 = UCase(string1)
'converts string to uppercase
string3 = LCase(string1)
'converts string to lowercase
string4 = string1.Substring(11, 6)
'returns a substring
string5 = string1.Clone
'clones a string
string6 = string1.GetHashCode
'gets the hashcode
WriteLine(string2)
WriteLine(string3)
WriteLine(string4)
WriteLine(string5)
WriteLine(string6)
Read()
End Sub

End Module

The image below displays output from above code.


Math Functions
Visual Basic provides support for handling Mathematical calculations. Math functions are stored in System.Math namespace. We need to import this namespace  when we work with Math functions. The functions built into Math class helps us calculate the Trigonometry values, Square roots,  logarithm values, etc. The following code puts some Math functions to work.

Imports System.Console
Imports System.Math
Module Module1

Sub Main()
WriteLine("Sine 90 is" & " " & Sin(90))
'display Sine90 value
WriteLine("Square root of 81 is " & " " & Sqrt(81))
'displays square root of 81
WriteLine("Log value of 12 is" & " " & Log(12))
'displays the logarithm value of 12
Read()
End Sub

End Module

The image below displays output from above code.

Arrays

Arrays are programming constructs that store data and allow us to access them by numeric index or subscript. Arrays helps us create shorter and simpler code in many situations. Arrays in Visual Basic .NET inherit from the Array class in the System namespace. All arrays in VB are zero based, meaning, the index of the first element is zero and they are numbered sequentially. You must specify the number of array elements by indicating the upper bound of the array. The upper bound is the numder that specifies the index of the last element of the array. Arrays are declared using Dim, ReDim, Static, Private, Public and Protected keywords. An array can have one dimension (liinear arrays) or more than one (multidimensional arrays). The dimensionality of an array refers to the number of subscripts used to identify an individual element. In Visual Basic we can specify up to 32 dimensions. Arrays do not have fixed size in Visual Basic.
The following code demonstrates arrays.

Imports System.Console
Module Module1

Sub Main()
Dim sport(5) As String
'declaring an array
sport(0) = "Soccer"
sport(1) = "Cricket"
sport(2) = "Rugby"
sport(3) = "Aussie Rules"
sport(4) = "BasketBall"
sport(5) = "Hockey"
'storing values in the array
WriteLine("Name of the Sport in the third location" & " " & sport(2))
'displaying value from array
End Sub

End Module

Understanding the Code
The above code declared a sport array of type string like this: Dim sport(5) as String. This sport array has 6 elements starting from sport(0) to sport(5). The first element of an array is always referred by zero index. The image below displays output from above code.


You can also declare an array without specifying the number of elements on one line, you must provide values for each element when initializing the array. The following lines demonstrate that:

Dim Test() as Integer
'declaring a Test array
Test=New Integer(){1,3,5,7,9,}

Reinitializing Arrays

We can change the size of an array after creating them. The ReDim statement assigns a completely new array object to the specified array variable. You use ReDim statement to change the number of elements in an array. The following lines of code demonstrate that. This code reinitializes the Test array declared above. 

Dim Test(10) as Integer
ReDim Test(25) as Integer
'Reinitializing the array

When using the Redim statement all the data contained in the array is lost. If you want to preserve existing data when reinitializing an array then you should use the Preserve keyword which looks like this:

Dim Test() as Integer={1,3,5}
'declares an array an initializes it with three members
ReDim Preserve Test(25)
'resizes the array and retains the the data in elements 0 to 2

Multidimensional Arrays
All arrays which were mentioned above are one dimensional or linear arrays. There are two kinds of multidimensional arrays supported by the .NET framework: Rectangular arrays and Jagged arrays.
Rectangular arrays
Rectangular arrays are arrays in which each member of each dimension is extended in each other dimension by the same length. We declare a rectangular array by specifying additional dimensions at declaration. The following lines of code demonstrate the declaration of a multidimensional array.

Dim rectArray(4, 2) As Integer
'declares an array of 5 by 3 members which is a 15 member array
Dim rectArray(,) As Integer = {{1, 2, 3}, {12, 13, 14}, {11, 10, 9}}
'setting initial values

Jagged Arrays
Another type of multidimensional array, Jagged Array, is an array of arrays in which the length of each array can differ. Example where this array can be used is to create a table in which the number of columns differ in each row. Say, if row1 has 3 columns, row2 has 3 columns then row3 can have 4 columns, row4 can have 5 columns and so on. The following code demonstrates jagged arrays.
Dim colors(2)() as String
'declaring an array of 3 arrays
colors(0)=New String(){"Red","blue","Green"}
initializing the first array to 3 members and setting values
colors(1)=New String(){"Yellow","Purple","Green","Violet"}
initializing the second array to 4 members and setting values
colors(2)=New String(){"Red","Black","White","Grey","Aqua"}
initializing the third array to 5 members and setting values

Enumeration, Exception Handling

Enumeration
Enumeration is a related set of constants. They are used when working with many constants of the same type. It's  declared with the Enum keyword.
Example

Imports System.Console
Module Module1

Enum Seasons
Summer = 1
Winter = 2
Spring = 3
Autumn = 4
End Enum

Sub Main()
Write("Summer is the" & Seasons.Summer & "season")
End Sub

End Module

Output of above code is the image below. To use a constant from the enumeration it should be referred like this, Seasons.Winter and so on.


Constants
When we have certain values that we frequently use while programming, we should use Constants. A value declared as constant is of fixed value that cannot be changed once set. Constants should be declared as Public if we want it to be accessed by all parts of the application. In Visual Basic .NET we use the Const keyword to declare a constant. The following line of code declares a constant: Public Const Pi as Double=3.14159265
Exception Handling
Exceptions are runtime errors that occur when a program is running and causes the program to abort without execution. Such kind of situations can be handled using Exception Handling. By placing specific lines of code in the application we can handle most of the errors that we may encounter and we can enable the application to continue running. VB .NET supports two ways to handle exceptions, Unstructured exception Handling using the on error goto statement and Structured exception handling using Try....Catch.....Finally
Let's look at the new kind of exception handling introduced in VB .NET which is the Structured Exception Handling. VB .NET uses Try....Catch....Finally block type exception handling. The syntax looks like this:
Module Module1
Sub Main()
Try
-
-
Catch e as Exception
-
-
Finally
End Try
End Sub
End Module
Example

Imports System.Console
Module Module1

Sub Main()
Dim a = 0, b = 1, c As Integer
Try
c = b / a
'the above line throws an exception
WriteLine("C is " & c)
Catch e As Exception
WriteLine(e)
'catching the exception
End Try
End Sub

End Module

The output of the above code displays a message stating the exception. The reason for the exception is because any number divided by zero is infinity. When working with Structured exception handling you can have multiple Catch blocks to handle different types of exceptions differently. The code in the Finally block is optional. If there is a Finally block in the code then that code is executed last.


Operators

Code Samples
Arithmetic Operators

Imports System.Console
Module Module1

Sub Main()
Dim x, y, z As Integer
x = 30
y = 20
z = x + y
WriteLine("Addition" & " = " & z)
z = x - y
WriteLine("Subtraction" & " = " & z)
z = x * y
WriteLine("Multiplication" & " = " & z)
z = x / y
WriteLine("Division" & " = " & z)
Read()
End Sub

End Module

The image below displays output from above code.


Concatenation Operators

Imports System.Console
Module Module1

Sub Main()
Dim str1, str2, str3, str4 As String
str1 = "Concatenation"
str2 = "Operators"
str3 = str1 + str2
WriteLine(str3)
str4 = str1 & str2
WriteLine(str4)
Read()
End Sub

End Module

The image below displays output from above code.


Comparison Operators

Imports System.Console
Module Module1


Sub Main()
Dim x, y As Integer
WriteLine("enter values for x and y ")
x = Val(ReadLine())
y = Val(ReadLine())
If x = y Then
WriteLine("x is equal to y")
ElseIf x < y Then
WriteLine("x is less than y")
ElseIf x > y Then
WriteLine("x is greater than y")
End If
Read()
End Sub

End Module

The image below displays output from above code.


Logical / Bitwise Operators

Imports System.Console
Module Module1

Sub Main()
Dim x As Boolean
x = Not 45 > 26
WriteLine("x not is false")
' x equals false
x = Not 26 > 87
' x equals True
WriteLine("x not is true")
Read()
End Sub

End Module

The image below displays output from above code.

 

Operators

Visual Basic comes with many built-in operators that allow us to manipulate data. An operator performs a function on one or more operands. For example, we add two variables with the "+" addition operator and store the result in a third variable with the "=" assignment operator like this: int x + int y = int z. The two variables (x ,y) are called operands. There are different types of operators in Visual Basic and they are described below in the order of their precedence.
Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations that involve calculation of numeric values. The table below summarizes them:


OperatorUse
^Exponentiation
-Negation (used to reverse the sign of the given value, exp -intValue)
*Multiplication
/Division
\Integer Division
ModModulus Arithmetic
+Addition
-Subtraction

Concatenation Operators
Concatenation operators join multiple strings into a single string. There are two concatenation operators, + and & as summarized below:

OperatorUse
+String Concatenation
&String Concatenation

Comparison Operators
A comparison operator compares operands and returns a logical value based on whether the comparison is true or not. The table below summarizes them:

OperatorUse
= Equality
<>Inequality
<Less than
>Greater than
>=Greater than or equal to
<=Less than or equal to

Logical / Bitwise Operators
The logical operators compare Boolean expressions and return a Boolean result. In short, logical operators are expressions which return a true or false result over a conditional expression. The table below summarizes them:

OperatorUse
Not Negation
AndConjunction
AndAlsoConjunction
Or Disjunction
OrElse Disjunction
Xor Disjunction

Data Type Conversion, File Extensions

Converting between Data types
In Visual Basic, data can be converted in two ways: implicitly, which means the conversion is performed automatically, and explicitly, which means you must perform the conversion.
Implict Conversions
Let's understand implicit conversions in code. The example below declares two variable, one of type double and the other integer. The double data type is assigned a value and is converted to integer type. When you run the code the result displayed is an integer value, in this case the value displayed is 132 instead of 132.31223.

Imports System.Console
Module Module1

Sub Main()
Dim d=132.31223 as Double
Dim i as Integer
i=d
WriteLine("Integer value is" & i)
End Sub

End Module

Explicit Conversions
When types cannot be implicitly converted you should convert them explicitly. This conversion is also called as cast. Explicit conversions are accomplished using CType function.
CType function for conversion
If we are not sure of the name of a particular conversion function then we can use the CType function. The above example with a CType function looks like this:

Imports System.Console
Module Module1

Sub Main()
Dim d As Double
d = 132.31223
Dim i As Integer
i = CType(d, i)
'two arguments, type we are converting from, to type desired
WriteLine("Integer value is" & i)
End Sub

End Module

Below is the list of conversion functions which we can use in VB .NET.
CBool - use this function to convert to Bool data type
CByte - use this function to convert to Byte data type
CChar - use this function to convert to Char data type
CDate - use this function to convert to Date type
CDbl - use this function to convert to Double data type
CDec - use this function to convert to Decimal data type
CInt - use this function to convert to Integer data type
CLng - use this function to convert to Long data type
CObj - use this function to convert to Object type
CShort - use this function to convert to Short data type
CSng - use this function to convert to Single data type
CString - use this function to convert to String data type
Attributes
Attributes are  those that lets us specify information about the items we are using in VB .NET. Attributes are enclosed in angle brackets(< >) and are used when VB .NET needs to know more beyond the standard syntax.
File Extensions in VB .NET
The files and their extensions which are created as part of the Windows Application Project and their meaning are summarized below:
.vbproj->A Visual Basic project
Form1.vb->A form's code
AssemblyInfo.VB->Information about an assembly, includes version information
.vbproj.user->Stores project user options
.sln->Solution file which stores solution's configuration
.suo-> Stores Solution user options
Form1.resx.NET->XML based resource template
bin directory->Directory for binary executables
obj directory->Directory for debugging binaries
Language Terminology
Briefly on some terminology when working with the language:
Module: Used to hold code
Variable: A named memory location of a specific data type used to hold some value
Procedure: A callable series of statements which may or may not return a value
Sub-Procedure: A procedure with no return value
Function: A procedure with return value
Methods: A procedure built into the class
Constructor: Special method used to initialize and customize the object. It has the same name as the class
Class: An OOP class which contains data and code
Object: An instance of a class
Arrays: Programming constructs that lets us access data by numeric index
Attributes: They are the items that specify information about other items being used in VB. NET