27
Integer Types in VB.NET... Integer types in VB.Net are used to represent whole numbers. Depending on the amount of memory required to store an integer the data type in VB.net is categorized as, Byte, Short, Integer and Long. The following table lists the data type and its size. Data Type Size in Bytes Byte 1 Short 2 Integ er 4 Long 8 Following statement shows how we can declare an integer variable in VB.NET. Dim x, y As Integer Here x and y are two integer variables and as they are not initialised with any number, they would be initialised to 0. Dim i As Short = 12 The variable i declared in this statement would hold value 12. VB.NET provides logical operators, And and AndAlso that can be used to help evaluate expressions. Consider following statement, If age < 10 And number > 4 Then // code End If Here we want that if the value of age is greater than 10, then the second condition should not be evaluated. Since the conditions given above are connected using And, both the conditions would get evaluated. In other words, even if the first condition evaluates to false, And evaluates the second condition. However, in case of AndAlso operator, it evaluates the second condition only if the first condition evaluates to true. For example, If age < 10 AndAlso number > 4 Then // code End If

VB dotnet

Embed Size (px)

DESCRIPTION

csharp,asp.net,sql,interview questions,techinterviews,aspdotnet,sqlserver2005

Citation preview

Page 1: VB dotnet

Integer Types in VB.NET...

Integer types in VB.Net are used to represent whole numbers. Depending on the amount of memory required to store an integer the data type in VB.net is categorized as, Byte, Short, Integer and Long. The following table lists the data type and  its size. 

 Data Type 

 Size in Bytes

 Byte   1

 Short   2

 Integer  4

 Long   8

Following statement shows how we can declare an integer variable in VB.NET.

Dim x, y As Integer

Here x and y are two integer variables and as they are not initialised with any number, they would be initialised to 0. 

Dim i As Short = 12

The variable i declared in this statement would hold value 12.

VB.NET provides logical operators, And and AndAlso that can be used to help evaluate expressions. Consider following statement,

If age < 10 And number > 4 Then// code

End If

Here we want that if the value of age is greater than 10, then the second condition should not be evaluated. Since the conditions given above are connected using And, both the conditions would get evaluated. In other words, even if the first condition evaluates to false, And evaluates the second condition. However, in case of AndAlso operator, it evaluates the second condition only if the first condition evaluates to true. For example, 

If age < 10 AndAlso number > 4 Then// code

End If

If the value of age is greater than 10, the evaluation of the expression stops and the operator would return false. Thus, using AndAlso helps evaluating expressions efficiently.

There are two types of procedures in VB.NET-Functions and Subroutines. The basic difference between the two is that a subroutine does not return a value whereas a function returns a value. Function is a collection of logical statements which perform a specific task and return some value. Hence whenever you want to return something to a calling function use a function and to display something use a subroutine. Thus, for displaying a

Page 2: VB dotnet

menu we would use a subroutine and for calculating a factorial of a number and returning it to the calling function we would use a function.

Constructor in VB .NET

In VB.NET the constructor name is not same as the name of the class. A keyword New is used to define a constructor. Following code snippet shows how to declare a constructor: 

Class sampleDim i As IntegerSub New( )

i = 5End Sub

End Class Module Module1

Sub Main( )Dim obj As sample

obj = New sample( )End Sub

End Module

In the above example in the class sample we have defined a constructor to initialise the data member i. In main( ) we have created an object obj of the class sample. As soon as the object gets created the constructor gets called and the value of i gets intialised to 5.

We can use the MinValue and MaxValue properties to get the minimum as well as maximum range of each data type. This is shown in following example.

Module RangesSub Main( )

Console.WriteLine("Byte Range: {0} to {1}", Byte.MinValue, Byte.MaxValue)Console.WriteLine("Short Range: {0} to {1}", Short.MinValue, Short.MaxValue)Console.WriteLine("Integer Range: {0} to {1}", Integer.MinValue, Integer.MaxValue)Console.WriteLine("Long Range: {0} to {1}", Long.MinValue, Long.MaxValue)

End SubEnd Module

Namespaces...

Much of interesting functionality available in VB .NET is provided by the .NET Framework Class Library. Namespaces are used to hold collection of related classes. Console I/O is provided by the .NET System.Console class. The WriteLine( ) method is used to display a line of text. 

System.Console.WriteLine ( "Hello World" )

Reference to System.Console.WriteLine may be shortened to Console.WriteLine if you import the System namespace.

Import System...Console.WriteLine ( "Hello World" )

Page 3: VB dotnet

The Import statement tells compiler to look in the System namespace before generating an error whenever an unknown class or function is referenced.

Value Types Vs Reference Types

In VB.NET variables are either value types or of reference types. The difference between the value type and reference type is that the data of value type gets stored on the stack and that of the reference type gets stored on the heap. The variables of the value types directly contain the data, whereas, reference types contain references (or addresses) of the data. Examples of value types are the primitive data types integer, floating points, structures whereas examples of reference types are arrays and classes

Arrays...

We can declare an array as shown below:

Dim arr( ) As Integerarr = New Integer ( 5 ) { }

Here, the first statement creates only a reference to one dimensional array. By default arr holds nothing. The second statement allocates memory for 5 integers. The space for arr is allocated on the stack. Space of array elements gets allocated on heap. The elements of arr would be 0 as by default array elements are initialised to zero. One more way of declaring an array is given below:

Dim arr( ) As Integer = { 1, 2 , 3 ,4 }

Here again arr is created on the stack and the actual array elements are created on the heap. These array elements are initialised with values 1, 2, 3, 4 respectively. Note that when we initialize an array at the same place where we are declaring it then there is no need of New statement.

In .NET arrays are implemented as objects. An array gets automatically derived from System.Array class. This is because when we create an array a class gets created from the System.Array class. This class internally maintains an array. An object of this class is also created to which the array reference points. Hence using the reference we can call methods and access properties of the System.Array class. In VB.NET the lower bound of an array is always zero. Thus with the statement Dim arr(3) As Integer an array of 4 elements get created.

VB.NET provides the flexibility to use Value types as Reference types, as and when required. Whenever a value type is converted into a reference type it is known as Boxing. On the other hand when a reference type is converted into value type it is known as Unboxing. Both the WriteLine( ) and the ReadLine( ) methods use this concept of Boxing and Unboxing respectively.

For example, consider following statement:

WriteLine ( Dim s As string, ParamArray arr( ) As Object ) 

Here, all the objects except the first are collected in the ParamArray of type Object. Hence there is no restriction on the number of parameters being printed in the list. In the WriteLine( ) method if we pass an integer variable, the compiler implicitly converts an integer variable ( value type )

Page 4: VB dotnet

into an object ( reference type ) using boxing and collects it as the first element of the ParamArray of objects.

Readline( ) method is an example of Unboxing. ReadLine( ) always returns a string which is a reference type. This reference type is explicitly converted into the value type that we want. For example, using CInt we can convert a string into an Integer, which is a value type.

Dim I As IntegerI = CInt ( Console.ReadLine( ) )

How do I create a structure?

Ans: The following code snippet shows how we can create a structure in VB.NET.

Structure aDim i As IntegerDim s As String Sub New ( ii as Integer, ss as String )

i = iis = ss

End Sub End Structure

Note that we cannot explicitly mention a zero-argument constructor within a structure. A zero-argument constructor is always provided by the compiler. However writing a multiple argument constructor within a structure is allowed.

Whenever we wish to group a few dissimilar data types, we must use structures because being a value type it gets allocated on the stack. Memory allocation on stack is always faster than on heap. However, if the structure is big then whenever we pass the structure variable as a parameter or assign it to another structure variable, the full contents of the structure variable gets copied. As against this for a class only the reference gets copied. It is more efficient to copy a 4 byte reference than copying the entire structure.

Why memory allocation for value types is faster than for reference types?

Ans: Memory allocation for value types is always faster than for reference types. This is because reference types are always accessed via references. Hence anytime our code refers to any member of an object on the heap, code must be generated and executed to dereference the reference in order to manipulate the object. This affects both size and speed. However in case of value types the variable itself represents an object. Hence there is no question of dereferencing in order to manipulate the object. This improves performance.

What are Primitive data types?

Ans: Data types that are directly supported by the compiler are called Primitive data types. Integers, Single, Double and Char types are all examples of primitive data types. Primitive data types map directly to the types that exist in the base class library. For example an Integer in VB.NET maps directly to System.Int32 type.

How do I declare variables as read only in VB.NET?

Ans: VB.NET provides a keyword ReadOnly which is used for variables which are to be

Page 5: VB dotnet

initialized at the time of building the objects. The following code shows how to declare variables as ReadOnly.

Module module1Class hotel

Public ReadOnly name As StringSub New ( ByVal n As String )

name = nEnd Sub

End Class

Sub main( )Dim h As New hotel ( "Tuli" )

End SubEnd Module

We cannot assign any value to a ReadOnly Variable. Hence the statement h.name = "CP" would give us an error. i.e h.name cannot be written on the left side of the assignment operator.

Properties In VB.NET...

Properties of a class are actually methods that work like data members .The properties are used to store and retrieve the values to and from the data members of the class. The following code shows how to declare a property called Length within a class called sample.

Module Module1Class sample

Dim len As IntegerProperty Length( ) As Integer

GetReturn len

End GetSet ( ByVal Value As Integer )

len = ValueEnd Set

End PropertyEnd ClassSub Main( )

Dim s As New sample( )s.Length = 10Dim l As Integer = s.LengthConsole.WriteLine( l )

End SubEnd Module

To store and retrieve the len data member of the class sample the Length property is used. A property has two special methods known as a Get accessor and a Set accessor. The Get accessor never accepts any value and the Set accessor never returns any value. The value collected by the Set accessor is stored in an implicit parameter called Value. The statement m.Length = 10 would invoke the Set accessor and the statement len = m.Length would invoke the Get accessor.

Page 6: VB dotnet

Interfaces in VB.NET...

Interfaces are similar to abstract classes. The following statements show how we can declare an interface called mouse. 

Interface mouseSub lbuttondown ( x As Integer, y As Integer )Sub rbuttondown ( x As Integer, y As Integer )

End Interface

Any class can implement the above interface and can provide separate implementation of the functions defined in the interface. Note that an interface contains only declarations of functions and does not contain any definitions. Following code snippet shows how a class can implement the above interface.

Class Mouse1 : Implements mouseSub lbuttondown ( x As Integer, y As Integer ) Implements mouse.lbuttondown

Console.WriteLine ( "Left Button : { 0 }, { 1 }", x, y )End SubSub rbuttondown ( x As Integer, y As Integer ) Implements mouse.rbuttondown

Console.WriteLine ( "Right Button : { 0 }, { 1 }", x, y )End Sub

End Class

Virtual Functions in VB.NET…

In VB .NET the keyword Overridable is used to indicate that a function is virtual. The Overridable keyword in VB.NET is similar to the keyword virtual in C++. Following code snippet shows how we can design a base class that has a virtual function.

Class shapeOverridable Sub draw( )

Console.WriteLine( " Shape" )End Sub

End Class

Any class that inherits the shape class can override the draw( ) method. For this it is necessary that draw( ) method should be preceded with the keyword Overrides in a derived class. This is shown in following code snippet.

Class line : Inherits shapeOverrides Sub draw( )

Console.WriteLine ( "Line" )End Sub

End Class

Conversion Functions In VB.NET...

VB.NET provides many conversion functions. Some of these functions are CInt, CBool, CStr, CLng, CDec, CSng, CShort.

CInt function converts any numeric expression to an Integer value as shown below:

Page 7: VB dotnet

Dim i As Integeri = CInt ( 10.5 )

CBool function convert expressions to Boolean values.

Dim check As BooleanDim a, b As Integera = 15b = 15check = CBool (a = b ) // 'True is assigned in check

CStr function converts a numeric value to String.

Dim i As Double = 42.34Dim s As Strings = CStr ( i )

These functions are inline functions. Hence execution is faster because there is no call to a procedure to perform the conversion.

Error Handling In VB.NET... 

The errors that occur at the time of execution of a program are known as exceptions. VB.NET provides a Try-Catch mechanism to handle exceptions. The Try block contains code expected to raise an exception. This code in the Try block executes until a statement, which raises an exception, is encountered. When an exception is encountered, the Catch block handles the exception by executing the code written in it. In the following program an IndexOutOfRangeException is raised. The CLR creates an object of the  IndexOutOfRangeException class and passes it to Catch block that accepts a reference to the IndexOutOfRangeException.

Module Module1Sub Main( )

Dim index As Integer = 6Dim val As Integer = 30Dim a ( 5 ) As IntegerTry

a ( index) = valCatch e As IndexOutOfRangeException

Console.WriteLine ( " Index out of bounds" )End TryConsole.WriteLine( " Remaining program" )

End SubEnd Module

The output of the above program would be:

Index out of bounds

How do I write code to navigate to previous and/or next record?

Ans: Add code to the handlers that move record pointer to previous and next record respectively, as shown below:

Page 8: VB dotnet

Private Sub Previous_Click ( ByVal sender As System.Object, ByVal e As System.EventArgs ) Handles Previous.Click

Dim str As String'dr is a private variable of type DataRowCollection added to Form classstr = dr ( count ).Item ( 0 ) 

'to move to previous record decrement count by 1

count -= 1 ' where count is a variable of type IntegerIf count < 0 Then

count = 0MsgBox ( "Reached First Record" )

End If

End Sub

Private Sub Next_Click ( ByVal sender As System.Object, ByVal e As System.EventArgs ) Handles Next.Click

'to move to next record increment count by 1count += 1

Dim str As Stringstr = dr ( count ).Item ( 0 ) ' where dr is a variable of type DataRowCollection 

If Count >= dr.Count - 1 Then

count = dr.Count - 2MsgBox ( "Reached Last Record" )

End If

End Sub

Virtual Functions in VB.NET…

In VB .NET the keyword Overridable is used to indicate that a function is virtual. The Overridable keyword in VB.NET is similar to the keyword virtual in C++. Following code snippet shows how we can design a base class that has a virtual function.

Class shapeOverridable Sub draw( )

Console.WriteLine( " Shape" )End Sub

End Class

Page 9: VB dotnet

Any class that inherits the shape class can override the draw( ) method. For this it is necessary that draw( ) method should be preceded with the keyword Overrides in a derived class. This is shown in following code snippet.

Class line : Inherits shapeOverrides Sub draw( )

Console.WriteLine ( "Line" )End Sub

End Class

How do I write pure virtual functions in VB.NET?

Ans: In VB.NET the pure virtual functions are written by writing the keyword MustOverride against the name of the method. The keyword MustOverride specifies that the method written in the base class must be overridden in the derived class. Like pure virtual functions a MustOverride method cannot have a body. Consider the following example:

MustInherit Class shapeMustOverride Sub draw( )

End ClassClass circle : Inherits shape

Overrides Sub draw( )Console.WriteLine ( "Circle" )

End SubEnd Class

Here, since the method draw( ) is declared as MustInherit in the base class shape, any class that inherits the class shape must override the draw( ) method. Hence the class circle which inherits shape class provides its own implementation of the draw( ) method.

How do I write code that would throw exceptions explicitly in VB.NET?

Ans: In VB.NET the Throw statement is used to throw an exception explicitly.

Class sampleSub fun ( i As Integer )

If i > 10 ThenThrow New Exception ( "Value out of range" )

ElseConsole.WriteLine ( i )

End IfEnd Sub

End ClassModule Module1

Sub Main( )Dim m As New sample( )Try

m.fun ( 20 )Catch e As Exception

Console.WriteLine ( e.Message( ) )End TryConsole.WriteLine ( "Remaining Program" )

End SubEnd Module

Page 10: VB dotnet

Here, the parameter passed to the method fun( ) is greater than 20 hence an exception would be raised. The Catch block catches the exception and displays the message "Value out of Range".

How do I write code to display two strings on two lines using Writeline( )?

Ans:  VB.NET provides a keyword NewLine which helps to achieve this purpose. In order to use this keyword we must import the namespace Microsoft.VisualBasic.ControlChars. Following statement shows how to use this keyword.

Console.WriteLine ( "hi" & NewLine & "hello" )

How do I change the size of an array in VB.NET?

Ans: VB.NET provides a keyword called Redim which enables us to change the size of an array that has been already declared. The following code snippet shows how to change the size of an array called arr from 6 elements to 11 elements.

Dim arr ( 5 ), i As IntegerFor i = 0 To UBound ( arr )

arr ( i ) = iNextReDim arr ( 10 ) 'The size of arr now becomes 11 ( as array always starts from 0th index)For i = 0 To UBound ( arr )

arr ( i ) = i * 10Next

Suppose we want to preserve the existing contents of an array then we have to use the keyword preserve along with Redim as shown below:

Redim preserve arr ( 10 )

How do I write a class that cannot be inherited?

Ans: VB.NET provides a keyword called NotInheritable which ensures that a class cannot be derived further. This is shown in following code snippet.

NotInheritable Class shapeSub draw( )

Console.WriteLine ( "Shape" )End Sub

End Class

Since the class shape is preceded with the keyword NotInheritable, any attempt to derive a class from the class shape leads to an error.

How do I create a form of elliptical shape?

Ans: To create a form of elliptical shape, write following code in the constructor of the Form1 class.

Public Sub New( )MyBase.New( )Dim gp As New GraphicsPath( )

Page 11: VB dotnet

gp.AddEllipse ( 20, 20, 140, 40 )Region = New Region ( gp )

End Sub

Here, first we have instantiated an object of the GraphicsPath class. This GraphicsPath class has various methods which can be used to create various user defined shapes. Using the AddEllipse( ) method of this class we have first created an elliptical shape.

We have then instantiated a new Region object and to its constructor we have passed this graphics path. Next to the Region property of the Form1 class we have assigned this newly created region. Due to this only that portion of the form would be visible which lies within this region. Note that for this it is necessary to import System.Drawing.Drawing2D namespace.

How do I write code to create a mirror image?

Ans: To create a mirror image write following code in Form1_Paint Event handler.

Sub Form1_Paint ( s As Object, e As PaintEventArgs ) Handles MyBase.PaintDim g As Graphics = e.GraphicsDim myimg As Image = Image.FromFile ( "C:\fcode.jpg" ) Dim mymat As Matrix = New Matrix( )mymat.Scale ( -1, 1 )mymat.Translate ( -350, 0 )g.Transform = mymatg.DrawImage ( myimg, 50, 50 )g.ResetTransform( )

End Sub

Here first we have used the shared method FromFile( ) of the Image class. This would return a reference to image which we have collected in the variable myimg. In order to create a mirror image we have to make use of transformations. To create a transformation matrix we have first created an object of the Matrix class. We have first scaled the matrix by passing a -1 as the first parameter to the Scale( ) method. Due to this all the x coordinates would be multiplied by -1. After multiplying this matrix with the coordinates of the image the resultant image would be the mirror image of the original. When we scale the coordinates of an image by multiplying them with -1 the resulting coordinates become negative. Hence they would not be visible as top left corner of the form is 0, 0. To bring the image back in the form we have to translate it by some x and y values. For this we multiply the co-ordinates by a negative number to make the resultant coordinates positive. Next we have assigned this resultant transformation matrix to the Transform property of the Graphics object. There onwards everything that gets drawn would be multiplied with the transformation matrix. Finally for drawing the image we have used the DrawImage( ) method.

What are Delegates and how do I declare a Delegate?

Ans: The word delegate means a representation of a function. A delegate is implemented as an object that stores address of a method in it. The class of this object is called a delegate class and is derived from System.MultiCastDelegate class. The following statement shows how to declare a delegate class.

delegate Sub del ( string ) 

When the compiler encounters this statement it creates a class named del and derives it from the System.MulticastDelegate class. Later when an object of the delegate class del is created, it

Page 12: VB dotnet

can hold address of a method whose return type is void and receives a string. To store address of a method say fun( ) inside a delegate object we need to first create a delegate object. This is done as shown below:

Dim d As New del ( AddressOf fun )

Here d is a reference to an object of del. The address of the fun( ) method is passed to the constructor of the delegate class which is created by the compiler. The constructor stores this address in the delegate object. To call the wrapped method we can now write the following statement:

d ( "Hi" )

Here d delegates (represents) fun( ) in true sense. 

In VB..NET an Enum cannot have a circular definition. For example we cannot declare an Enum as shown below:

Enum emp As Integerskilled = highlyskilledsemiskilledhighlyskilledunskilled

End Enum

Here the value of skilled depends on its own value and hence is an error. We can however declare the Enum as shown below:

Enum emp As Integerskilledsemiskilledhighlyskilled = skilledunskilled

End Enum

Now if we print the members of the Enum in the order in which they are defined then we will get output as 0, 1, 0 and 1. The member skilled gets initialized to 0, the semiskilled to 1 ( 0 +1), highlyskilled to 0 again and unskilled to 1 ( 0 + 1).

How do I draw an icon on the form?

Ans: To draw an icon on the form we need to create an object of the Icon class by supplying the file name of the '.ico' file and then calling the DrawIcon( ) method of the Graphics class. Suppose that the reference of the graphics object is in g, then we can write the following:

Dim i As Icon New ( "C:\myicon.ico" )g.DrawIcon ( i, 10, 20 ) 

where 10, 20 denote the top left coordinates from where the icon would be drawn.

What is MergeOrder? When is it used?

Page 13: VB dotnet

Ans: MergeOrder is a property of the MenuItem class. This property gets or sets a value indicating the relative position of the menu item when it is merged with another. For example, suppose we create an MDI application. Now we add a MainMenu control containing some MenuItems to both the parent and the child window. If the child window has a set of menu items that we want to display in the parent window's main menu, we can create a MainMenu as part of both the forms and set some values to the MergeOrder property of the MenuItems of both the forms. So now when the child window is activated, its MainMenu is merged with the MainMenu of the parent window. While merging, the order of the menu items is according to the MergeOrder property.

How do ASP.NET pages support Cookieless Sessions?

Ans: By default, ASP.NET pages, like ASP, use cookies to correlate the session state with every user. Hence if the browser does not support cookies, then there arises a problem. ASP.NET however supports cookieless session state. Cookieless sessions are enabled by adding cookieless = “true’ to the sessionState element in the web.config file. 

In this case ASP.NET correlates users and the session states by passing the session id in the URL. The value seen in parenthesis in the browser’s address bar is the session ID. Before returning the page to the client, ASP.NET inserts the session ID into the URL. When the page posts back to the server, ASP.NET strips the session ID from the URL and uses it to associate the request with the session.

What is a Mobile Web Forms page?

Ans: Mobile web forms page is a specialized Microsoft ASP.NET Web Forms page. As with any other Web Forms page, a mobile Web Forms page is a text file with an '.aspx' file extension. This page contains a set of mobile Web Form controls— ASP.NET server controls that can adaptively render WML script.

We can program mobile pages and controls by using device-independent properties, methods, and events. When supported device requests a mobile Web Forms page, the page and controls automatically produce a rendering suitable for the device. Ordinary ASP.NET Web Forms pages can contain only one form per page. However, because mobile devices typically have smaller screens, a mobile Web Forms page allows several forms to be defined. 

When a client accesses a page for the first time, the first form is shown by default. You can programmatically navigate to other forms. To be able to develop mobile applications and use Mobile SDK we need to download the MobileIT.exe and install the msi from msdn.microsoft.com

How do I write code to show a bitmap in a picture box and save the picture along with changes if some drawing is done on it?

Ans: Follow the steps as listed below:1. On the form place a picture box named pb and a botton named save.

2. Add following variables in the form class.

Dim sourcefile As StringDim i As ImageDim st, en As PointDim p As PenDim newbitmap As Bitmap

Page 14: VB dotnet

3. Add following code in the constructor to show bitmap in the picture box.

Public Sub New( )MyBase.New( )'This call is required by the Windows Form Designer.InitializeComponent( )'Add any initialization after the InitializeComponent( ) callsourcefile = "C:\MyPicture.bmp"Try

i = Image.FromFile ( sourcefile )pb.Image = inewbitmap = New Bitmap ( i )

Catch ex As ExceptionMessageBox.Show ( ex.Message )

End TryEnd Sub

4. Create bitmap in memory using the Bitmap class. Then whatever drawing needs to be done in the MouseMove handler will be done on this bitmap by creating Graphics Context of the bitmap which in our case is gi. We will create Graphics context of Picture Box say g for example.Then write following code in the MouseMove handler.

Private Sub pb_MouseMove ( ByVal sender As Object, ByVal e As                            System.Windows.Forms.MouseEventArgs )                             Handles pb.MouseMove

p = New Pen ( Color.Red )Dim gi As Graphics = Graphics.FromImage ( newbitmap )Dim g As Graphicsg = pb.CreateGraphics

If ( e.Button = MouseButtons.Left ) Thenen = New Point ( e.X, e.Y )g.DrawLine ( p, st, en )gi.DrawLine ( p, st, en )gi.Dispose( )st = en

End IfEnd Sub

5. On clicking save button this image should get saved into another file say ‘C:\MyPicture1.bmp’. To do so we just have to call the Save function of the Bitmap class. Add following code to this function.

Private Sub save_Click ( ByVal sender As System.Object,                      ByVal e As System.EventArgs)                       Handles save.Click 

TryDim newfile As String = "C:\MyPicture1.bmp"newbitmap.Save ( newfile )newbitmap.Dispose( )

Catch ex As ExceptionMessageBox.Show ( ex.Message )

End TryEnd Sub

Page 15: VB dotnet

How do I write code to show check boxes within a listview control and on checking a particular check box the associated text should get written in the text box.? Every time checking the check box the text should get appended in the text box. And on unchecking a particular check box appropriate text should get erased from the text box 

Ans: Create an application and place a listview control named list and a text box named message on the form. Set the CheckBoxes property of list view to true. Add the check boxes through the Items (Collection) property of the list view control. Set the Text property of each item.

Now we want that when the check box in the list is checked the corresponding text should get displayed in the text box and when unchecked the text should get erased from the text box. For this add the ItemCheck handler in the form class and write following code in it.

Private Sub list_ItemCheck ( ByVal sender As Object, ByVal e As                      System.Windows.Forms.ItemCheckEventArgs                      ) Handles list.ItemCheck

Dim icoll As ListViewItemCollection = list.ItemsDim litem As ListViewItem = icoll.Item(e.Index)Dim i As IntegerIf e.NewValue = CheckState.Checked Then

message.Text = message.Text & litem.Textmessage.Text = message.Text & " "

ElseIf e.NewValue = CheckState.Unchecked Then Dim l As Integer = litem.Text.Lengthi = message.Text.IndexOf(litem.Text)message.Text = message.Text.Remove(i, l + 1)

End If End Sub

How do I show a large size bitmap into a small size picture box by using the transformation techniques?

Ans: Create a windows application. Place a picture box named pb and a button named Show on the form. On clicking the button the file should get displayed in the picture box. Add code shown below to the button handler.

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

Dim i As Imagei = Image.FromFile("C:\picutre.bmp")

Dim w As Integer = i.Width ' image widthDim h As Integer = i.Height ' image height

Dim pw As Integer = pb.Width ' picture box widthDim ph As Integer = pb.Height ' picture box height

Dim perw As Single = pw * 100 / w Dim perh As Single = ph * 100 / h

Dim mat As New Matrix()mat.Scale(perw / 100, perh / 100)

Page 16: VB dotnet

Dim pbg As Graphics = pb.CreateGraphics 

pbg.Transform = matpbg.DrawImage(i, 0, 0)

End Sub

To send mail via outlook express in VB.NET

Create a Windows application and place a button SendMail named sendmail on the form and a text box named emailaddr on it. After writing the email address in the text box when the SendMail Button is clicked OutLook Express Dialog Box should get popped up having the email address which is written in the text box.

For this write the following code in the sendmail button handler

Private Sub sendmail_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mailsend.Click

If emailaddr.Text = "" then MessageBox.Show("Enter The Email Address") Return

End If

System.Diagnostics.Process.Start("mailto:" & emailaddr)

End Sub

How do I make use of LinkLabel control in a program?

Ans: Follow the steps listed below:

        1. Create a Windows Application.        2. Place on it a LinkLabel control named as link.         3. Set the Text property of link as "http://www.funducode.com/". 

On clicking link an appropriate web page should get opened. To make it work add the LinkClicked event handler and write code to it as given below:

Private Sub link_LinkClicked ( ByVal sender As Object,  ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs ) Handles link.LinkClicked

System.Diagnostics.Process.Start(link.Text ) End Sub

How do I write code that sends an e-mail?

Ans: Create a Windows Application. Place four Text Boxes labeled as emailaddr, fromaddr, emailmessage and emailsubject used for—entering the destination email address, sending email address, writing message and writing subject respectively. Also add a button SendMail named sendmail on the form. On entering the email address in the text box and on writing the message in the emailmessage text box when the SendMail button is clicked the mail should be sent to the proper address. To do so we will use SMTPMail class, and to use it we need to add a reference in our solution. Click on 'View' menu and select 'Solution Explorer'. Right-click on

Page 17: VB dotnet

'references', select 'Add Reference' option. Then select 'System.Web.dll'. Click select and then press OK. As a result, System.Web reference will get added in our solution.

Now, we will have to import the namespace System.Web.Mail. For that write the following import statement in the Form1.vb at the top.

Imports System.Web.Mail

Then, write following code in the Click event handler of the SendMail button.

Private Sub sendmail_Click ( ByVal sender As System.Object, ByVal e As System.EventArgs )Handles sendmail.Click

If emailaddr.Text = "" ThenMessageBox.Show ( "Please enter email address" )Return

End If

Dim myMail As New MailMessage( )myMail.From = fromaddr.TextmyMail.To = emailaddr.TextmyMail.Subject = emailsubject .TextmyMail.BodyFormat = MailFormat.TextmyMail.Body = message.TextSmtpMail.Send ( myMail )

End Sub

How do I write code that pops up a context sensitive menu on right clicking onto a combo box?

Ans: Follow the steps given below. 

1. Create a Windows Application and place a combo box named cb on the form. Add a context menu on the form named     combomenu and add an item cadd in the menu. 

2. Set the text property of the menu item cadd as "ADD".

3. Set the ContextMenu property of the combo box as combomenu. 

4. Add the Click event handler for the cadd menu item and enter code given below in it.

Private Sub cadd_Click ( ByVal sender As System.Object, ByVal e As System.EventArgs ) Handles cadd.Click

If cb.FindStringExact(cb.Text) = -1 Then cb.Items.Add(cb.Text)

End If End Sub

Here, we have not only added a context sensitive menu but also given a provision  that on clicking the menu item 'ADD", the text typed in the combo box should get added in the dropdown list. If the text is already present in the dropdown list it would not get added to the list.

How do I write code that uses ListView control to display list of records?

Page 18: VB dotnet

Ans: Create a Windows application and place three text boxes named empname, age, sal for writing name, age and salary of an employee. Place a button called 'Add' and a list view control on the form. On clicking 'Add' button information in all edit boxes should get added in the list view under appropriate column. Set the View property of list as Details. Click on the Columns property in the Property Window for list, add three columns to list in ColumnHeader Collection Editor and set their Text Properties as 'Name', 'Age', 'Salary' respectively. Then add following code in the Click Event handler of the 'Add' button.

Private Sub adddata_Click ( ByVal sender As System.Object, ByVal e As System.EventArgs ) Handles adddata.Click

Dim litem As New ListViewItem( )litem.Text = empname.Textlitem.SubItems.Add ( age.Text )litem.SubItems.Add ( sal.Text )list.Items.Add ( litem )

End Sub

How do I write code that sends a mail via outlook express?

Ans: Create a Windows application and place a button named sendmail and a text box named emailaddr on the form. On adding the email address to the text box if sendmail button is clicked 'OutLook Express' dialog box should get popped up with an email address written in the text box. To get so write following code in the button handler.

Private Sub sendmail_Click ( ByVal sender As System.Object, ByVal e As System.EventArgs ) Handles mailsend.Click

If emailaddr.Text = "" then MessageBox.Show ( "Enter The Email Address" ) Return

End IfSystem.Diagnostics.Process.Start ( "mailto:" & emailaddr )

End Sub

How do I write code that shows check boxes in the list view and displays the text in a message box when a check box is checked?

Ans: Create a Windows application and place a list view control named as list on the form. Set its ShowCheckBoxes property to true and view property as List. Add items in the list by clicking on Items property in the 'Properties'. Set the Text property of each item in the 'ListViewItem Collection' editor. To be able to make use of ListviewCollection class write following statement in  Form1.vb at the top.

Imports System.Windows.Forms.ListView

Now, add ItemCheck event handler of list and write following code in the ItemCheck event handler.

Private Sub list_ItemCheck ( ByVal sender As Object, ByVal e As System.Windows.Forms.ItemCheckEventArgs )

Handles list.ItemCheck Dim icoll As ListViewItemCollection = list.ItemsDim litem As ListViewItem = icoll.Item ( e.Index )

Page 19: VB dotnet

If e.NewValue = CheckState.Checked ThenMessageBox.Show ( litem.Text )End If

End Sub

How do I display an icon of an application in system tray and display context menu for it?

Ans: Create a Windows application and place NotifyIcon control on the form. Name it as trayicon. Add an icon to your application and name it as myicon. Set the Icon property of trayicon as myicon. Place a ContextMenu control on the form and name it as trayconmenu. Add one item to the menu having text 'Exit' and name as ex. Set the ContextMenu property of trayicon as myconmenu.

Add handler for click event for ex menu item and write following code in it.

Private Sub ex_Click ( ByVal sender As System.Object, ByVal e As System.EventArgs ) Handles ex.Click

Application.Exit( ) End Sub

How do I write code to display contents of a file in a multi-line text box?

Ans: Create a Windows application. Place two text boxes named filepath and filetext, and two buttons named browse and open on the form. Set the two properties Mutiline and ScrollBars of filetext to True and Both respectively. Then drag OpenFileDialog control on the form. Name it as opendlg and set its Filter property to 'Text files (*.txt)|*.txt'. Add click event handlers for both the buttons browse and open. Write following code in button handler for browse:

Private Sub browse_Click ( ByVal sender As System.Object, ByVal e As System.EventArgs ) Handles browse.Click

opendlg.ShowDialog( ) If opendlg.FileName <> "" Then

filepath.Text = opendlg.FileName End If

End Sub

Here, we have used StreamReader class hence write following line at the top in Form1.Vb file

Imports System.IO

Now, add following code in the click event handler of open button.

Private Sub open_Click ( ByVal sender As System.Object, ByVal e As System.EventArgs ) Handles open.Click

Dim reader As StreamReader = New StreamReader ( filepath.Text )filetext.Text = reader.ReadToEnd( )reader.Close( )

End Sub

Page 20: VB dotnet

How do I write code to display a Splash Screen for an application?

Ans: Create a Windows application. Add another form named SplashForm to the application by selection Project | Add | Windows Form menu item. Insert a picture box on the SplashForm. Copy a '.bmp' say 'Splash.bmp' to the project. Set the Image property of the picture box to the file name 'Splash.bmp'. Change the BackColor and BorderStyle property of SplashForm to White and none respectively. Set the TransparencyKey of SplashForm as White. Then write following code in the constructor of Form1.

Public Sub New( ) MyBase.New()'This call is required by the Windows Form Designer.InitializeComponent( )'Add any initialization after the InitializeComponent() callDim f As New SplashForm( )

End Sub

Write following code in constructor of SplashForm.

Public Sub New( ) MyBase.New( )'This call is required by the Windows Form Designer.InitializeComponent( )'Add any initialization after the InitializeComponent( ) callShow( )Application.DoEvents( )Thread.Sleep ( 1000 )Dispose( )

End Sub

Accessing Database Using OLEDB.NET...

Create a database called bank and add a table called account with three fields accno, name and balance. Create a console application. In this application we will connect to the database and display the contents of the table account on the console output. To be able to use class OLEDBDataReader  write following line at the top in 'Module1.Vb'.

Imports System.Data.OleDb

Create the connection string and the command strings. Then create OleDbConnection object and OleDbCommand object. Using the command object execute the query. Write code in Sub Main( ) as shown below:

Sub Main( ) Dim connectionstr As String = "Provider = Microsoft.Jet.OLEDB.4.0 ;Data Source = c:\bank.mdb"Dim commandstr As String = "SELECT accno, name, balance from account"

Dim connection As New OleDbConnection ( connectionstr )Dim command As New OleDbCommand ( commandstr, connection )connection.Open( )Dim r As OleDbDataReader = command.ExecuteReader( )

Page 21: VB dotnet

While r.Read( ) Console.WriteLine ( r(0) & r(1) & r(2) )

End Whileconnection.Close( )

End Sub

How do I declare variables as read only in VB.NET?

Ans: VB.NET provides a keyword ReadOnly which is used for variables which are to be initialized at the time of building the objects. The following code shows how to declare variables as ReadOnly.

Module module1Class hotel

Public ReadOnly name As StringSub New ( ByVal n As String )

name = nEnd Sub

End Class

Sub main( )Dim h As New hotel ( "Tuli" )

End SubEnd Module

We cannot assign any value to a ReadOnly Variable. Hence the statement h.name = "CP" would give us an error. i.e h.name cannot be written on the left side of the assignment operator.

Properties In VB.NET...

Properties of a class are actually methods that work like data members .The properties are used to store and retrieve the values to and from the data members of the class. The following code shows how to declare a property called Length within a class called sample.

Module Module1Class sample

Dim len As IntegerProperty Length( ) As Integer

GetReturn len

End GetSet ( ByVal Value As Integer )

len = ValueEnd Set

End PropertyEnd ClassSub Main( )

Dim s As New sample( )s.Length = 10Dim l As Integer = s.LengthConsole.WriteLine( l )

End SubEnd Module

Page 22: VB dotnet

To store and retrieve the len data member of the class sample the Length property is used. A property has two special methods known as a Get accessor and a Set accessor. The Get accessor never accepts any value and the Set accessor never returns any value. The value collected by the Set accessor is stored in an implicit parameter called Value. The statement m.Length = 10 would invoke the Set accessor and the statement len = m.Length would invoke the Get accessor.