Saturday, 28 September 2013

ASPDOTNET WITH VBDOTNET - MASTERPAGE BASICS MANOHAR GOUD



ASP.NET master pages enable you to create a page layout (a master page) that you can use with selected or all pages (content pages) in your Web site. Master pages can greatly simplify the task of creating a consistent look for your site.

ASP.NET master pages allow you to create a consistent layout for the pages in your application. A single master page defines the look and feel and standard behavior that you want for all of the pages (or a group of pages) in your application. You can then create individual content pages that contain the content you want to display. When users request the content pages, they merge with the master page to produce output that combines the layout of the master page with the content from the content page.

Master pages actually consist of two pieces, the master page itself and one or more content pages.

A master page is an ASP.NET file with the extension .master (for example, MySite.master) with a predefined layout that can include static text, HTML elements, and server controls. The master page is identified by a special @ Master directive that replaces the @ Page directive that is used for ordinary .aspx pages. 

Master Pages

<%@ Master Language="C#" %>
or
<%@ Page Language="VB" MasterPageFile="~/MasterPages/Master1.master" Title="Content Page" %>
 
 
<% @ Master Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 
    1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server" >
    <title>Master page title</title>
</head>
<body>
    <form id="form1" runat="server">
        <table>
            <tr>
                <td><asp:contentplaceholder id="Main" runat="server" /></td>
                <td><asp:contentplaceholder id="Footer" runat="server" /></td>
            </tr>
        </table>
    </form>
</body>
</html>
 
or
 
<%@ Master Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 
    1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server" >
    <title>Master page title</title>
</head>
<body>
    <form id="form1" runat="server">
        <table>
           <tr>
               <td><asp:contentplaceholder id="Main" runat="server" /></td>
               <td><asp:contentplaceholder id="Footer" runat="server" /></td>
           </tr>
        </table>
    </form>
</body>
</html>
 
 

Content Pages

 

<%@ Page Language="C#" MasterPageFile="~/MasterPages/Master1.master" Title="Content Page"%>
or
<%@ Page Language="VB" MasterPageFile="~/MasterPages/Master1.master" Title="Content Page" %>
 
Replacing placeholder content
MasterPagesMerge graphic
 <% @ Page Language="VB" MasterPageFile="~/Master.master" Title="Content Page 1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="Main" Runat="Server">
    Main content.
</asp:Content>
    
<asp:Content ID="Content2" ContentPlaceHolderID="Footer" Runat="Server" >
    Footer content.
</asp:content>
 
or
 
<% @ Page Language="C#" MasterPageFile="~/Master.master" Title="Content Page 1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="Main" Runat="Server">
    Main content.
</asp:Content>
    
<asp:Content ID="Content2" ContentPlaceHolderID="Footer" Runat="Server" >
    Footer content.
</asp:content>
 

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copying existing code, text, and control elements repeatedly; using framesets; using include files for common elements; using ASP.NET user controls; and so on. Advantages of master pages include the following:
  • They allow you to centralize the common functionality of your pages so that you can make updates in just one place.
  • They make it easy to create one set of controls and code and apply the results to a set of pages. For example, you can use controls on the master page to create a menu that applies to all pages.
  • They give you fine-grained control over the layout of the final page by allowing you to control how the placeholder controls are rendered.
  • They provide an object model that allows you to customize the master page from individual content pages.

Run-time Behavior of Master Pages

At run time, master pages are handled in the following sequence:
  1. Users request a page by typing the URL of the content page.
  2. When the page is fetched, the @ Page directive is read. If the directive references a master page, the master page is read as well. If this is the first time the pages have been requested, both pages are compiled.
  3. The master page with the updated content is merged into the control tree of the content page.
  4. The content of individual Content controls is merged into the corresponding ContentPlaceHolder control in the master page.
  5. The resulting merged page is rendered to the browser.
The process is illustrated in the following diagram.
Master pages at run time
MasterPagesMerge graphic
From the user's perspective, the combined master and content pages are a single, discrete page. The URL of the page is that of the content page.
From a programming perspective, the two pages act as separate containers for their respective controls. The content page acts as a container for the master page. However, you can reference public master-page members from code in the content page, as described in the next section.
Note that the master page becomes a part of the content page. In effect, the master page acts in much the same way a user control acts — as a child of the content page and as a container within that page. In this case, however, the master page is the container for all of the server controls that are rendered to the browser. The control tree for a merged master and content page looks something like this:
Page
    Master Page
        (Master page markup and controls)
        ContentPlaceHolder
            Content page markup and server controls
        (Master page markup and controls)
        ContentPlaceHolder
            Content page markup and server controls
        (Master page markup and controls)
 

 

 

PROGRAMMING OF MASTER PAGE

 

' Gets a reference to a TextBox control inside a ContentPlaceHolder
Dim mpContentPlaceHolder As ContentPlaceHolder
Dim mpTextBox As TextBox
mpContentPlaceHolder = _
    CType(Master.FindControl("ContentPlaceHolder1"), _
    ContentPlaceHolder)
If Not mpContentPlaceHolder Is Nothing Then
    mpTextBox = CType(mpContentPlaceHolder.FindControl("TextBox1"), _
        TextBox)
    If Not mpTextBox Is Nothing Then
        mpTextBox.Text = "TextBox found!"
    End If
End If

' Gets a reference to a Label control that is not in a 
' ContentPlaceHolder control
Dim mpLabel As Label
mpLabel = CType(Master.FindControl("masterPageLabel"), Label)
If Not mpLabel Is Nothing Then
    Label1.Text = "Master page label = " + mpLabel.Text
End If
 
 
 
 
 
 
 
Sub Page_PreInit(ByVal sender As Object, ByVal e As EventArgs) _
        Handles Me.PreInit
    Me.MasterPageFile = "~/NewMaster.master"
End Sub
 
 
 
 
 
Public Class BaseMaster
    Inherits MasterPage
    Public Overridable ReadOnly Property MyTitle() As String
        Get
            Return "BaseMaster Title"
        End Get
    End Property
End Class
 
   

 

<%@ Master Language="VB"  Inherits="BaseMaster" 
    ClassName="MasterBlue" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" 
   "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<script runat="server">
    ' No property here that overrrides the MyTitle property of the base master.
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>No title</title>
</head>
<body>
    <form id="form1" runat="server">
    <div style="background-color:LightBlue">
        <asp:contentplaceholder id="ContentPlaceHolder1" 
            runat="server">
        Content from MasterBlue.
        </asp:contentplaceholder>
    </div>
    </form>
</body>
</html>
 
 
<%@ Master Language="VB" Inherits="BaseMaster" 
    ClassName="MasterGreen" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" 
    "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<script runat="server">
    Public Overrides ReadOnly Property MyTitle() As String
        Get
            Return "MasterGreen Title"
        End Get
    End Property
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">   
    <title>No title</title>
</head>
<body>
    <form id="form1" runat="server">
    <div style="background-color:LightGreen">
        <asp:contentplaceholder id="ContentPlaceHolder1" runat="server">
            Content from MasterGreen.
        </asp:contentplaceholder>
    </div>
    </form>
</body>
</html>
 
 
 
<%@ Page Language="VB" Title="Content Page" MasterPageFile="~/MasterBlue.master"%>
<%@ MasterType TypeName="BaseMaster" %>
<script runat="server">
    
    Protected Sub Page_PreInit(ByVal sender As Object, 
            ByVal e As System.EventArgs)
        Me.MasterPageFile = "MasterBlue.master"
        If Request.QueryString("color") = "green" Then
            Me.MasterPageFile = "MasterGreen.master"
        End If
        Me.Title = Master.MyTitle
    End Sub
</script>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    Content from Content page.
</asp:Content>
 
 
or
 
 
c#
 
// Gets a reference to a TextBox control inside a ContentPlaceHolder
ContentPlaceHolder mpContentPlaceHolder;
TextBox mpTextBox;
mpContentPlaceHolder = 
    (ContentPlaceHolder)Master.FindControl("ContentPlaceHolder1");
if(mpContentPlaceHolder != null)
{
    mpTextBox = (TextBox) mpContentPlaceHolder.FindControl("TextBox1");
    if(mpTextBox != null)
    {
        mpTextBox.Text = "TextBox found!";
    }
}

// Gets a reference to a Label control that is not in a 
// ContentPlaceHolder control
Label mpLabel = (Label) Master.FindControl("masterPageLabel");
if(mpLabel != null)
{
    Label1.Text = "Master page label = " + mpLabel.Text;
} 
 
 
 
 
void Page_PreInit(Object sender, EventArgs e)
{
    this.MasterPageFile = "~/NewMaster.master";
}
 
 
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public class BaseMaster : System.Web.UI.MasterPage
{
    public virtual String MyTitle
    {
        get { return "BaseMaster Title"; }
    }
}
 
 
<%@ Master Language="C#" Inherits="BaseMaster" 
    ClassName="MasterBlue" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" 
   "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<script runat="server">
    // No property here that overrrides the MyTitle property of the base master.
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>No title</title>
</head>
<body>
    <form id="form1" runat="server">
    <div style="background-color:LightBlue">
        <asp:contentplaceholder id="ContentPlaceHolder1" 
            runat="server">
        Content from MasterBlue.
        </asp:contentplaceholder>
    </div>
    </form>
</body>
</html>
 
 
 
<%@ Master Language="C#" Inherits="BaseMaster" 
    ClassName="MasterGreen" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" 
    "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<script runat="server">
    public override String MyTitle
    { 
        get { return "MasterGreen Title"; } 
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">   
    <title>No title</title>
</head>
<body>
    <form id="form1" runat="server">
    <div style="background-color:LightGreen">
        <asp:contentplaceholder id="ContentPlaceHolder1" 
            runat="server">
            Content from MasterGreen.
        </asp:contentplaceholder>
    </div>
    </form>
</body>
</html>
 
 
 
<%@ Page Language="C#" Title="Content Page" MasterPageFile="~/MasterBlue.master"%>
<%@ MasterType TypeName="BaseMaster" %>
<script runat="server">
    protected void Page_PreInit(Object sender, EventArgs e)
    {
        this.MasterPageFile = "MasterBlue.master";
        if(Request.QueryString["color"] == "green")
        {
            this.MasterPageFile = "MasterGreen.master";
        }
        this.Title = Master.MyTitle;
    }
</script>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" 
        Runat="Server">
    Content from Content page.
</asp:Content>
 
 
 
 
Both master pages and content pages can contain event handlers for controls. For controls, events are handled locally—a control in a content page raises an event in the content page, and a control in the master page raises an event in the master page. Controls events are not sent from the content page to the master page. Similarly, you cannot handle an event from a master page control in a content page.
In some cases, the same event is raised in both the content and the master page. For example, both pages raise Init and Load events. The general rule for how events are raised is that the initialization events are raised from the innermost control to the outermost one, and all other events are raised from the outermost control to the innermost one. It is helpful to remember that the master page is merged into the content page and treated as a control in the content page.
The following is the sequence in which events occur when a master page is merged with a content page:
  1. Master page controls Init event.
  2. Content controls Init event.
  3. Master page Init event.
  4. Content page Init event.
  5. Content page Load event.
  6. Master page Load event.
  7. Content controls Load event.
  8. Content page PreRender event.
  9. Master page PreRender event.
  10. Master page controls PreRender event.
  11. Content controls PreRender event.
The sequence of events in master and content pages rarely is important for you as page developer.
 
 
 Sub Page_Load()
    Dim mpContentPlaceHolder As ContentPlaceHolder
    Dim mpTextBox As TextBox
    mpContentPlaceHolder = _
        CType(Master.FindControl("ContentPlaceHolder1"), _
        ContentPlaceHolder)
    If Not mpContentPlaceHolder Is Nothing Then
        mpTextBox = CType(mpContentPlaceHolder. _
            FindControl("TextBox1"), TextBox)
        If Not mpTextBox Is Nothing Then
            mpTextBox.Text = "TextBox found!"
        End If
    End If

    ' Gets a reference to a Label control not in a 
    ' ContentPlaceHolder
    Dim mpLabel As Label
    mpLabel = CType(Master.FindControl("masterPageLabel"), Label)
    If Not mpLabel Is Nothing Then
        Label1.Text = "Master page label = " + mpLabel.Text
    End If
End Sub
 
 
or
 
pContentPlaceHolder = 
      (ContentPlaceHolder)Master.FindControl("ContentPlaceHolder1");
    if(mpContentPlaceHolder != null)
    {
        mpTextBox = 
            (TextBox) mpContentPlaceHolder.FindControl("TextBox1");
        if(mpTextBox != null)
        {
            mpTextBox.Text = "TextBox found!";
        }
    }
    
    // Gets a reference to a Label control that not in 
    // a ContentPlaceHolder
    Label mpLabel = (Label) Master.FindControl("masterPageLabel");
    if(mpLabel != null)
    {
        Label1.Text = "Master page label = " + mpLabel.Text;
    }
}
 
 
 
 
 
 
 
 
 
 
 
 
 

 








Thursday, 26 September 2013

ASPDOTNET WITH VBDOTNET - VBDOTNET BASICS MANOHAR GOUD


A procedure is a group of statements that together perform a task, when called. After the procedure is executed, the control returns to the statement calling the procedure. VB.Net has two types of procedures:
  • Functions
  • Sub procedures or Subs
Functions return a value, where Subs do not return a value.

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:
[Modifiers] Function FunctionName [(ParameterList)] As ReturnType
    [Statements]
End Function
Where,
Tutorial content goes here.....
  • Modifiers: specifiy 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

Example

Following code snippet shows a function FindMax that takes two integer values and returns the larger of the two.
Function FindMax(ByVal num1 As Integer, ByVal num2 As Integer) As Integer
   ' local variable declaration */
   Dim result As Integer
   If (num1 > num2) Then
       result = num1
   Else
       result = num2
   End If
   FindMax = result
End Function

Function Returning a Value

In VB.Net a function can return a value to the calling code in two ways:
  • By using the return statement
  • By assigning the value to the function name
The following example demonstrates using the FindMax function:
Module myfunctions
   Function FindMax(ByVal num1 As Integer, ByVal num2 As Integer) As Integer
      ' local variable declaration */
      Dim result As Integer
      If (num1 > num2) Then
          result = num1
      Else
          result = num2
      End If
      FindMax = result
   End Function
   Sub Main()
      Dim a As Integer = 100
      Dim b As Integer = 200
      Dim res As Integer
      res = FindMax(a, b)
      Console.WriteLine("Max value is : {0}", res)
      Console.ReadLine()
   End Sub
End Module
When the above code is compiled and executed, it produces following result:
Max value is : 200

Recursive Function

A function can call itself. This is known as recursion. Following is an example that calculates factorial for a given number using a recursive function:
Module myfunctions
   Function factorial(ByVal num As Integer) As Integer
      ' local variable declaration */
      Dim result As Integer
      If (num = 1) Then
          Return 1
      Else
          result = factorial(num - 1) * num
          Return result
      End If
   End Function
   Sub Main()
      'calling the factorial method
      Console.WriteLine("Factorial of 6 is : {0}", factorial(6))
      Console.WriteLine("Factorial of 7 is : {0}", factorial(7))
      Console.WriteLine("Factorial of 8 is : {0}", factorial(8))
      Console.ReadLine()
   End Sub
End Module
When the above code is compiled and executed, it produces following result:
Factorial of 6 is: 720
Factorial of 7 is: 5040
Factorial of 8 is: 40320

Param Arrays

At times, while declaring a function or sub procedure you are not sure of the number of arguments passed as a parameter. VB.Net param arrays (or parameter arrays) come into help at these times.
The following example demonstrates this:
Module myparamfunc
   Function AddElements(ParamArray arr As Integer()) As Integer
      Dim sum As Integer = 0
      Dim i As Integer = 0
      For Each i In arr
          sum += i
      Next i
      Return sum
   End Function
   Sub Main()
      Dim sum As Integer
      sum = AddElements(512, 720, 250, 567, 889)
      Console.WriteLine("The sum is: {0}", sum)
      Console.ReadLine()
   End Sub
End Module
When the above code is compiled and executed, it produces following result:
The sum is: 2938

Passing Arrays as Function Arguments

You can pass an array as a function argument in VB.Net. The following example demonstrates this:
Module arrayParameter
   Function getAverage(ByVal arr As Integer(), ByVal size As Integer) As Double
      'local variables
       Dim i As Integer
       Dim avg As Double
       Dim sum As Integer = 0
       For i = 0 To size - 1
           sum += arr(i)
       Next i
       avg = sum / size
       Return avg
    End Function
    Sub Main()
        ' an int array with 5 elements '
        Dim balance As Integer() = {1000, 2, 3, 17, 50}
        Dim avg As Double
        'pass pointer to the array as an argument 
        avg = getAverage(balance, 5)
        ' output the returned value '
        Console.WriteLine("Average value is: {0} ", avg)
        Console.ReadLine()
    End Sub
End Module
When the above code is compiled and executed, it produces following result:
Average value is: 214.4


As we mentioned in the previous chapter, Sub procedures are procedures that do not return any value. We have been using the Sub procedure Main in all our examples. We have been writing console applications so far, in these tutorials. When these applications start, the control goes to the Main Sub procedure, and it in turn, runs any other statements constituting the body of the program.

Defining Sub Procedures

The Sub statement is used to declare the name, parameter and the body of a sub procedure. The syntax for the Sub statement is:
[Modifiers] Sub SubName [(ParameterList)] 
    [Statements]
End Sub
Where,
  • Modifiers: specifiy the access level of the procedure; possible values are: Public, Private, Protected, Friend, Protected Friend and information regarding overloading, overriding, sharing, and shadowing.
  • SubName: indicates the name of the Sub
  • ParameterList: specifies the list of the parameters

Example

The following example demonstrates a Sub procedure CalculatePay that takes two parameters hours and wagesand displays the total pay of an employee:
Module mysub
   Sub CalculatePay(ByVal hours As Double, ByVal wage As Decimal)
      'local variable declaration
      Dim pay As Double
      pay = hours * wage
      Console.WriteLine("Total Pay: {0:C}", pay)
   End Sub
   Sub Main()
      'calling the CalculatePay Sub Procedure
      CalculatePay(25, 10)
      CalculatePay(40, 20)
      CalculatePay(30, 27.5)
      Console.ReadLine()
   End Sub
End Module
When the above code is compiled and executed, it produces following result:
Total Pay: $250.00
Total Pay: $800.00
Total Pay: $825.00

Passing Parameters by Value

This is the default mechanism for passing parameters to a method. In this mechanism, when a method is called, a new storage location is created for each value parameter. The values of the actual parameters are copied into them. So, the changes made to the parameter inside the method have no effect on the argument.
In VB.Net, you declare the reference parameters using the ByVal keyword. The following example demonstrates the concept:
Module paramByval
   Sub swap(ByVal x As Integer, ByVal y As Integer)
      Dim temp As Integer
      temp = x ' save the value of x 
      x = y    ' put y into x 
      y = temp 'put temp into y 
   End Sub
   Sub Main()
      ' local variable definition 
      Dim a As Integer = 100
      Dim b As Integer = 200
      Console.WriteLine("Before swap, value of a : {0}", a)
      Console.WriteLine("Before swap, value of b : {0}", b)
      ' calling a function to swap the values '
      swap(a, b)
      Console.WriteLine("After swap, value of a : {0}", a)
      Console.WriteLine("After swap, value of b : {0}", b)
      Console.ReadLine()
   End Sub
End Module
When the above code is compiled and executed, it produces following result:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200
It shows that there is no change in the values though they had been changed inside the function.

Passing Parameters by Reference

A reference parameter is a reference to a memory location of a variable. When you pass parameters by reference, unlike value parameters, a new storage location is not created for these parameters. The reference parameters represent the same memory location as the actual parameters that are supplied to the method.
In VB.Net, you declare the reference parameters using the ByRef keyword. The following example demonstrates this:
Module paramByref
   Sub swap(ByRef x As Integer, ByRef y As Integer)
      Dim temp As Integer
      temp = x ' save the value of x 
      x = y    ' put y into x 
      y = temp 'put temp into y 
   End Sub
   Sub Main()
      ' local variable definition 
      Dim a As Integer = 100
      Dim b As Integer = 200
      Console.WriteLine("Before swap, value of a : {0}", a)
      Console.WriteLine("Before swap, value of b : {0}", b)
      ' calling a function to swap the values '
      swap(a, b)
      Console.WriteLine("After swap, value of a : {0}", a)
      Console.WriteLine("After swap, value of b : {0}", b)
      Console.ReadLine()
   End Sub
End Module
When the above code is compiled and executed, it produces following result:
Before swap, value of a : 100
Before swap, value of b : 200
After swap, value of a : 200
After swap, value of b : 100

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:
[ <attributelist> ] [ accessmodifier ] [ Shadows ] [ MustInherit | NotInheritable ] [ Partial ] _
Class name [ ( Of typelist ) ]
    [ Inherits classname ]
    [ Implements interfacenames ]
    [ statements ]
End Class
Where,
  • attributelist is a list of attributes that apply to the class. Optional.
  • accessmodifier defines the access levels of the class, it has values as - Public, Protected, Friend, Protected Friend and Private. Optional.
  • Shadows indicate that the variable re-declares and hides an identically named element, or set of overloaded elements, in a base class. Optional.
  • MustInherit specifies that the class can be used only as a base class and that you cannot create an object directly from it, i.e, an abstract class. Optional.
  • NotInheritable specifies that the class cannot be used as a base class.
  • Partial indicates a partial definition of the class
  • Inherits specifies the base class it is inheriting from
  • Implements specifies the interfaces the class is inheriting from
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 following result:
Volume of Box1 : 210
Volume of Box2 : 1560

Member Functions and Encapsulation

A member function of a class is a function that has its definition or its prototype within the class definition like any other variable. It operates on any object of the class of which it is a member, and has access to all the members of a class for that object.
Member variables are attributes of an object (from design perspective) and they are kept private to implement encapsulation. These variables can only be accessed using the public member functions.
Let us put above concepts to set and get the value of different class members in a class:
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
      Public Sub setLength(ByVal len As Double)
          length = len
      End Sub
      Public Sub setBreadth(ByVal bre As Double)
          breadth = bre
      End Sub
      Public Sub setHeight(ByVal hei As Double)
          height = hei
      End Sub
      Public Function getVolume() As Double
          Return length * breadth * height
      End Function
   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.setLength(6.0)
      Box1.setBreadth(7.0)
      Box1.setHeight(5.0)
      
      'box 2 specification
      Box2.setLength(12.0)
      Box2.setBreadth(13.0)
      Box2.setHeight(10.0)
      
      ' volume of box 1
      volume = Box1.getVolume()
      Console.WriteLine("Volume of Box1 : {0}", volume)

      'volume of box 2
      volume = Box2.getVolume()
      Console.WriteLine("Volume of Box2 : {0}", volume)
      Console.ReadKey()
   End Sub
End Module
When the above code is compiled and executed, it produces following result:
Volume of Box1 : 210
Volume of Box2 : 1560

Constructors and Destructors

A class constructor is a special member Sub of a class that is executed whenever we create new objects of that class. A constructor has the name New and it does not have any return type.
Following program explain the concept of constructor:
Class Line
   Private length As Double    ' Length of a line
   Public Sub New()   'constructor
      Console.WriteLine("Object is being created")
   End Sub
   Public Sub setLength(ByVal len As Double)
      length = len
   End Sub
     
   Public Function getLength() As Double
      Return length
   End Function
   Shared Sub Main()
      Dim line As Line = New Line()
      'set line length
      line.setLength(6.0)
      Console.WriteLine("Length of line : {0}", line.getLength())
      Console.ReadKey()
   End Sub
End Class
When the above code is compiled and executed, it produces following result:
Object is being created
Length of line : 6
A default constructor does not have any parameter but if you need a constructor can have parameters. Such constructors are called parameterized constructors. This technique helps you to assign initial value to an object at the time of its creation as shown in the following example:
Class Line
   Private length As Double    ' Length of a line
   Public Sub New(ByVal len As Double)   'parameterised constructor
      Console.WriteLine("Object is being created, length = {0}", len)
      length = len
   End Sub
   Public Sub setLength(ByVal len As Double)
      length = len
   End Sub
       
   Public Function getLength() As Double
      Return length
   End Function
   Shared Sub Main()
      Dim line As Line = New Line(10.0)
      Console.WriteLine("Length of line set by constructor : {0}", line.getLength())
      'set line length
      line.setLength(6.0)
      Console.WriteLine("Length of line set by setLength : {0}", line.getLength())
      Console.ReadKey()
   End Sub
End Class
When the above code is compiled and executed, it produces following result:
Object is being created, length = 10
Length of line set by constructor : 10
Length of line set by setLength : 6
A destructor is a special member Sub of a class that is executed whenever an object of its class goes out of scope.
A destructor has the name Finalize and it can neither return a value nor can it take any parameters. Destructor can be very useful for releasing resources before coming out of the program like closing files, releasing memories etc.
Destructors cannot be inherited or overloaded.
Following example explain the concept of destructor:
Class Line
   Private length As Double    ' Length of a line
   Public Sub New()   'parameterised constructor
      Console.WriteLine("Object is being created")
   End Sub
   Protected Overrides Sub Finalize()  ' destructor
      Console.WriteLine("Object is being deleted")
   End Sub
   Public Sub setLength(ByVal len As Double)
      length = len
   End Sub
   Public Function getLength() As Double
      Return length
   End Function
   Shared Sub Main()
      Dim line As Line = New Line()
      'set line length
      line.setLength(6.0)
      Console.WriteLine("Length of line : {0}", line.getLength())
      Console.ReadKey()
   End Sub
End Class
When the above code is compiled and executed, it produces following result:
Object is being created
Length of line : 6
Object is being deleted

Shared Members of a VB.Net Class

We can define class members as static using the Shared keyword. When we declare a member of a class as Shared it means no matter how many objects of the class are created, there is only one copy of the member.
The keyword Shared implies that only one instance of the member exists for a class. Shared variables are used for defining constants because their values can be retrieved by invoking the class without creating an instance of it.
Shared variables can be initialized outside the member function or class definition. You can also initialize Shared variables inside the class definition.
You can also declare a member function as Shared. Such functions can access only Shared variables. The Shared functions exist even before the object is created.
The following example demonstrates the use of shared members:
Class StaticVar
   Public Shared num As Integer
   Public Sub count()
      num = num + 1
   End Sub
   Public Shared Function getNum() As Integer
      Return num
   End Function
   Shared Sub Main()
      Dim s As StaticVar = New StaticVar()
      s.count()
      s.count()
      s.count()
      Console.WriteLine("Value of variable num: {0}", StaticVar.getNum())
      Console.ReadKey()
   End Sub
End Class
When the above code is compiled and executed, it produces following result:
Value of variable num: 3

Inheritance

One of the most important concepts in object-oriented programming is that of inheritance. Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and fast implementation time.
When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the baseclass, and the new class is referred to as the derived class.

Base & Derived Classes:

A class can be derived from more than one class or interface, which means that it can inherit data and functions from multiple base class or interface.
The syntax used in VB.Net for creating derived classes is as follows:
<access-specifier> Class <base_class>
...
End Class
Class <derived_class>: Inherits <base_class>
...
End Class
Consider a base class Shape and its derived class Rectangle:
' Base class
Class Shape
   Protected width As Integer
   Protected height As Integer
   Public Sub setWidth(ByVal w As Integer)
      width = w
   End Sub
   Public Sub setHeight(ByVal h As Integer)
      height = h
   End Sub
End Class
' Derived class
Class Rectangle : Inherits Shape
   Public Function getArea() As Integer
      Return (width * height)
   End Function
End Class
Class RectangleTester
   Shared Sub Main()
      Dim rect As Rectangle = New Rectangle()
      rect.setWidth(5)
      rect.setHeight(7)
      ' Print the area of the object.
      Console.WriteLine("Total area: {0}", rect.getArea())
      Console.ReadKey()
   End Sub 
End Class
When the above code is compiled and executed, it produces following result:
Total area: 35

Base Class Initialization

The derived class inherits the base class member variables and member methods. Therefore the super class object should be created before the subclass is created. The super class or the base class is implicitly known as MyBasein VB.Net
The following program demonstrates this:
' Base class
Class Rectangle
   Protected width As Double
   Protected length As Double
   Public Sub New(ByVal l As Double, ByVal w As Double)
      length = l
      width = w
   End Sub
   Public Function GetArea() As Double
      Return (width * length)
   End Function
   Public Overridable Sub Display()
      Console.WriteLine("Length: {0}", length)
      Console.WriteLine("Width: {0}", width)
      Console.WriteLine("Area: {0}", GetArea())
   End Sub
   'end class Rectangle  
End Class
'Derived class
Class Tabletop : Inherits Rectangle
   Private cost As Double
   Public Sub New(ByVal l As Double, ByVal w As Double)
      MyBase.New(l, w)
   End Sub
   Public Function GetCost() As Double
      Dim cost As Double
      cost = GetArea() * 70
      Return cost
   End Function
   Public Overrides Sub Display()
      MyBase.Display()
      Console.WriteLine("Cost: {0}", GetCost())
   End Sub
    'end class Tabletop
End Class
Class RectangleTester
   Shared Sub Main()
      Dim t As Tabletop = New Tabletop(4.5, 7.5)
      t.Display()
      Console.ReadKey()
   End Sub
End Class
When the above code is compiled and executed, it produces following result:
Length: 4.5
Width: 7.5
Area: 33.75
Cost: 2362.5
VB.Net supports multiple inheritance.

An exception is a problem that arises during the execution of a program. An exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero.
Exceptions provide a way to transfer control from one part of a program to another. VB.Net exception handling is built upon four keywords: Try, Catch, Finally and Throw.
  • Try: A Try block identifies a block of code for which particular exceptions will be activated. It's followed by one or more Catch blocks.
  • Catch: A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The Catch keyword indicates the catching of an exception.
  • Finally: The Finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not.
  • Throw: A program throws an exception when a problem shows up. This is done using a Throw keyword.

Syntax

Assuming a block will raise and exception, a method catches an exception using a combination of the Try and Catch keywords. A Try/Catch block is placed around the code that might generate an exception. Code within a Try/Catch block is referred to as protected code, and the syntax for using Try/Catch looks like the following:
Try
    [ tryStatements ]
    [ Exit Try ]
[ Catch [ exception [ As type ] ] [ When expression ]
    [ catchStatements ]
    [ Exit Try ] ]
[ Catch ... ]
[ Finally
    [ finallyStatements ] ]
End Try
You can list down multiple catch statements to catch different type of exceptions in case your try block raises more than one exception in different situations.

Exception Classes in .Net Framework

In the .Net Framework exceptions are represented by classes. The exception classes in .Net Framework are mainly directly or indirectly derived from the System.Exception class. Some of the exception classes derived from the System.Exception class are the System.ApplicationException and System.SystemException classes.
The System.ApplicationException class supports exceptions generated by application programs. So the exceptions defined by the programmers should derive from this class.
The System.SystemException class is the base class for all predefined system exception.
The following table provides some of the predefined exception classes derived from the Sytem.SystemException class:
Exception ClassDescription
System.IO.IOExceptionHandles I/O errors.
System.IndexOutOfRangeExceptionHandles errors generated when a method refers to an array index out of range.
System.ArrayTypeMismatchExceptionHandles errors generated when type is mismatched with the array type.
System.NullReferenceExceptionHandles errors generated from deferencing a null object.
System.DivideByZeroExceptionHandles errors generated from dividing a dividend with zero.
System.InvalidCastExceptionHandles errors generated during typecasting.
System.OutOfMemoryExceptionHandles errors generated from insufficient free memory.
System.StackOverflowExceptionHandles errors generated from stack overflow.

Handling Exceptions

VB.Net provides a structured solution to the exception handling problems in the form of try and catch blocks. Using these blocks the core program statements are separated from the error-handling statements.
These error handling blocks are implemented using the Try, Catch and Finally keywords. Following is an example of throwing an exception when dividing by zero condition occurs:
Module exceptionProg
   Sub division(ByVal num1 As Integer, ByVal num2 As Integer)
      Dim result As Integer
      Try
          result = num1 \ num2
      Catch e As DivideByZeroException
          Console.WriteLine("Exception caught: {0}", e)
      Finally
          Console.WriteLine("Result: {0}", result)
      End Try
   End Sub
   Sub Main()
      division(25, 0)
      Console.ReadKey()
  End Sub
End Module
When the above code is compiled and executed, it produces following result:
Exception caught: System.DivideByZeroException: Attempted to divide by zero. 
at ...
Result: 0

Creating User-Defined Exceptions

You can also define your own exception. User defined exception classes are derived from theApplicationException class. The following example demonstrates this:
Module exceptionProg
   Public Class TempIsZeroException : Inherits ApplicationException
      Public Sub New(ByVal message As String)
          MyBase.New(message)
      End Sub
   End Class
   Public Class Temperature
      Dim temperature As Integer = 0
      Sub showTemp()
          If (temperature = 0) Then
              Throw (New TempIsZeroException("Zero Temperature found"))
          Else
              Console.WriteLine("Temperature: {0}", temperature)
          End If
      End Sub
   End Class
   Sub Main()
      Dim temp As Temperature = New Temperature()
      Try
          temp.showTemp()
      Catch e As TempIsZeroException
          Console.WriteLine("TempIsZeroException: {0}", e.Message)
      End Try
      Console.ReadKey()
   End Sub
End Module
When the above code is compiled and executed, it produces following result:
TempIsZeroException: Zero Temperature found

Throwing Objects

You can throw an object if it is either directly or indirectly derived from the System.Exception class.
You can use a throw statement in the catch block to throw the present object as:
Throw [ expression ]
The following program demonstrates this:
Module exceptionProg
   Sub Main()
      Try
          Throw New ApplicationException("A custom exception _
    is being thrown here...")
      Catch e As Exception
          Console.WriteLine(e.Message)
      Finally
          Console.WriteLine("Now inside the Finally Block")
      End Try
      Console.ReadKey()
   End Sub
End Module
When the above code is compiled and executed, it produces following result:
A custom exception is being thrown here...
Now inside the Finally Block

A file is a collection of data stored in a disk with a specific name and a directory path. When a file is opened for reading or writing, it becomes a stream.
The stream is basically the sequence of bytes passing through the communication path. There are two main streams: the input stream and the output stream. The input stream is used for reading data from file (read operation) and the output stream is used for writing into the file (write operation).

VB.Net I/O Classes

The System.IO namespace has various class that are used for performing various operation with files, like creating and deleting files, reading from or writing to a file, closing a file etc.
The following table shows some commonly used non-abstract classes in the System.IO namespace:
I/O ClassDescription
BinaryReaderReads primitive data from a binary stream.
BinaryWriterWrites primitive data in binary format.
BufferedStreamA temporary storage for a stream of bytes.
DirectoryHelps in manipulating a directory structure.
DirectoryInfoUsed for performing operations on directories.
DriveInfoProvides information for the drives.
FileHelps in manipulating files.
FileInfoUsed for performing operations on files.
FileStreamUsed to read from and write to any location in a file.
MemoryStreamUsed for random access to streamed data stored in memory.
PathPerforms operations on path information.
StreamReaderUsed for reading characters from a byte stream.
StreamWriterIs used for writing characters to a stream.
StringReaderIs used for reading from a string buffer.
StringWriterIs used for writing into a string buffer.

The FileStream Class

The FileStream class in the System.IO namespace helps in reading from, writing to and closing files. This class derives from the abstract class Stream.
You need to create a FileStream object to create a new file or open an existing file. The syntax for creating aFileStream object is as follows:
Dim <object_name> As FileStream = New FileStream(<file_name>, <FileMode Enumerator>, <FileAccess Enumerator>, <FileShare Enumerator>)
For example, for creating a FileStream object F for reading a file named sample.txt:
Dim f1 As FileStream = New FileStream("test.dat", FileMode.OpenOrCreate, FileAccess.ReadWrite)
ParameterDescription
FileMode
The FileMode enumerator defines various methods for opening files. The members of the FileMode enumerator are:
  • Append: It opens an existing file and puts cursor at the end of file, or creates the file, if the file does not exist.
  • Create: It creates a new file.
  • CreateNew: It specifies to the operating system, that it should create a new file.
  • Open: It opens an existing file.
  • OpenOrCreate: It specifies to the operating system that it should open a file if it exists, otherwise it should create a new file.
  • Truncate: It opens an existing file and truncates its size to zero bytes.
FileAccess
FileAccess enumerators have members: Read, ReadWrite and Write.
FileShare
FileShare enumerators have the following members:
  • Inheritable: It allows a file handle to pass inheritance to the child processes
  • None: It declines sharing of the current file
  • Read: It allows opening the file for reading
  • ReadWrite: It allows opening the file for reading and writing
  • Write: It allows opening the file for writing

Example:

The following program demonstrates use of the FileStream class:
Imports System.IO
Module fileProg
   Sub Main()
      Dim f1 As FileStream = New FileStream("test.dat", _
              FileMode.OpenOrCreate, FileAccess.ReadWrite)
      Dim i As Integer
      For i = 0 To 20
          f1.WriteByte(CByte(i))
      Next i
      f1.Position = 0
      For i = 0 To 20
          Console.Write("{0} ", f1.ReadByte())
      Next i
      f1.Close()
      Console.ReadKey()
   End Sub
End Module
When the above code is compiled and executed, it produces following result:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 -1

Advanced File Operations in VB.Net

The preceding example provides simple file operations in VB.Net. However, to utilize the immense powers of System.IO classes, you need to know the commonly used properties and methods of these classes.
We will discuss these classes and the operations they perform, in the following sections. Please click the links provided to get to the individual sections:
Topic and Description
Reading from and Writing into Text files
It involves reading from and writing into text files. The StreamReader and StreamWriter class helps to accomplish it.
Reading from and Writing into Binary files
It involves reading from and writing into binary files. The BinaryReader and BinaryWriter class helps to accomplish this.
Manipulating the Windows file system
It gives a VB.Net programamer the ability to browse and locate Windows files and directories.

The StreamReader and StreamWriter classes are used for reading from and writing data to text files. These classes inherit from the abstract base class Stream, which supports reading and writing bytes into a file stream.

The StreamReader Class

The StreamReader class also inherits from the abstract base class TextReader that represents a reader for reading series of characters. The following table describes some of the commonly used methods of the StreamReader class:
S.NMethod Name & Purpose
1Public Overrides Sub Close
It closes the StreamReader object and the underlying stream, and releases any system resources associated with the reader.
2Public Overrides Function Peek As Integer
Returns the next available character but does not consume it.
3Public Overrides Function Read As Integer
Reads the next character from the input stream and advances the character position by one character.

Example:

The following example demonstrates reading a text file named Jamaica.txt. The file reads:
Down the way where the nights are gay
And the sun shines daily on the mountain top
I took a trip on a sailing ship
And when I reached Jamaica
I made a stop
Imports System.IO
Module fileProg
   Sub Main()
      Try
          ' Create an instance of StreamReader to read from a file. 
          ' The using statement also closes the StreamReader. 
          Using sr As StreamReader = New StreamReader("e:/jamaica.txt")
              Dim line As String
              ' Read and display lines from the file until the end of  
              ' the file is reached. 
              line = sr.ReadLine()
              While (line <> Nothing)
                  Console.WriteLine(line)
                  line = sr.ReadLine()
              End While
          End Using
      Catch e As Exception
          ' Let the user know what went wrong.
          Console.WriteLine("The file could not be read:")
          Console.WriteLine(e.Message)
      End Try
      Console.ReadKey()
   End Sub
End Module
Guess what it displays when you compile and run the program!

The StreamWriter Class

The StreamWriter class inherits from the abstract class TextWriter that represents a writer, which can write a series of character.
The following table shows some of the most commonly used methods of this class:
S.NMethod Name & Purpose
1Public Overrides Sub Close
Closes the current StreamWriter object and the underlying stream.
2Public Overrides Sub Flush
Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream.
3Public Overridable Sub Write ( value As Boolean ) 
Writes the text representation of a Boolean value to the text string or stream. (Inherited from TextWriter.)
4Public Overrides Sub Write ( value As Char ) 
Writes a character to the stream.
5Public Overridable Sub Write ( value As Decimal ) 
Writes the text representation of a decimal value to the text string or stream.
6Public Overridable Sub Write ( value As Double ) 
Writes the text representation of an 8-byte floating-point value to the text string or stream.
7Public Overridable Sub Write ( value As Integer ) 
Writes the text representation of a 4-byte signed integer to the text string or stream.
8Public Overrides Sub Write ( value As String ) 
Writes a string to the stream.
9Public Overridable Sub WriteLine
Writes a line terminator to the text string or stream.
The above list is not exhaustive. For complete list of methods please visit Microsoft's documentation

Example:

The following example demonstrates writing text data into a file using the StreamWriter class:
Imports System.IO
Module fileProg
   Sub Main()
      Dim names As String() = New String() {"Zara Ali", _
         "Nuha Ali", "Amir Sohel", "M Amlan"}
      Dim s As String
      Using sw As StreamWriter = New StreamWriter("names.txt")
          For Each s In names
              sw.WriteLine(s)
          Next s
      End Using
      ' Read and show each line from the file. 
      Dim line As String
      Using sr As StreamReader = New StreamReader("names.txt")
          line = sr.ReadLine()
          While (line <> Nothing)
              Console.WriteLine(line)
              line = sr.ReadLine()
          End While
      End Using
      Console.ReadKey()
   End Sub
End Module
When the above code is compiled and executed, it produces following result:
Zara Ali
Nuha Ali
Amir Sohel
M Amlan 

The BinaryReader and BinaryWriter classes are used for reading from and writing to a binary file.

The BinaryReader Class

The BinaryReader class is used to read binary data from a file. A BinaryReader object is created by passing aFileStream object to its constructor.
The following table shows some of the commonly used methods of the BinaryReader class.
S.NMethod Name & Purpose
1Public Overridable Sub Close
It closes the BinaryReader object and the underlying stream.
2Public Overridable Function Read As Integer
Reads the characters from the underlying stream and advances the current position of the stream.
3Public Overridable Function ReadBoolean As Boolean
Reads a Boolean value from the current stream and advances the current position of the stream by one byte.
4Public Overridable Function ReadByte As Byte
Reads the next byte from the current stream and advances the current position of the stream by one byte.
5Public Overridable Function ReadBytes ( count As Integer ) As Byte() 
Reads the specified number of bytes from the current stream into a byte array and advances the current position by that number of bytes.
6Public Overridable Function ReadChar As Char
Reads the next character from the current stream and advances the current position of the stream in accordance with the Encoding used and the specific character being read from the stream.
7Public Overridable Function ReadChars ( count As Integer ) As Char() 
Reads the specified number of characters from the current stream, returns the data in a character array, and advances the current position in accordance with the Encoding used and the specific character being read from the stream.
8Public Overridable Function ReadDouble As Double
Reads an 8-byte floating point value from the current stream and advances the current position of the stream by eight bytes.
9Public Overridable Function ReadInt32 As Integer
Reads a 4-byte signed integer from the current stream and advances the current position of the stream by four bytes.
10Public Overridable Function ReadString As String 
Reads a string from the current stream. The string is prefixed with the length, encoded as an integer seven bits at a time.

The BinaryWriter Class

The BinaryWriter class is used to write binary data to a stream. A BinaryWriter object is created by passing a FileStream object to its constructor.
The following table shows some of the commonly used methods of the BinaryWriter class.
S.NFunction Name & Description
1Public Overridable Sub Close
It closes the BinaryWriter object and the underlying stream.
2Public Overridable Sub Flush
Clears all buffers for the current writer and causes any buffered data to be written to the underlying device.
3Public Overridable Function Seek ( offset As Integer, origin As SeekOrigin ) As Long 
Sets the position within the current stream.
4Public Overridable Sub Write ( value As Boolean ) 
Writes a one-byte Boolean value to the current stream, with 0 representing false and 1 representing true.
5Public Overridable Sub Write ( value As Byte ) 
Writes an unsigned byte to the current stream and advances the stream position by one byte.
6Public Overridable Sub Write ( buffer As Byte() ) 
Writes a byte array to the underlying stream.
7Public Overridable Sub Write ( ch As Char ) 
Writes a Unicode character to the current stream and advances the current position of the stream in accordance with the Encoding used and the specific characters being written to the stream.
8Public Overridable Sub Write ( chars As Char() ) 
Writes a character array to the current stream and advances the current position of the stream in accordance with the Encoding used and the specific characters being written to the stream.
9Public Overridable Sub Write ( value As Double ) 
Writes an eight-byte floating-point value to the current stream and advances the stream position by eight bytes.
10Public Overridable Sub Write ( value As Integer ) 
Writes a four-byte signed integer to the current stream and advances the stream position by four bytes.
11Public Overridable Sub Write ( value As String ) 
Writes a length-prefixed string to this stream in the current encoding of the BinaryWriter, and advances the current position of the stream in accordance with the encoding used and the specific characters being written to the stream.
For complete list of methods, please visit Microsoft's documentation.

Example

The following example demonstrates reading and writing binary data:
Imports System.IO
Module fileProg
   Sub Main()
      Dim bw As BinaryWriter
      Dim br As BinaryReader
      Dim i As Integer = 25
      Dim d As Double = 3.14157
      Dim b As Boolean = True
      Dim s As String = "I am happy"
      'create the file
      Try
          bw = New BinaryWriter(New FileStream("mydata", FileMode.Create))
      Catch e As IOException
          Console.WriteLine(e.Message + "\n Cannot create file.")
          Return
      End Try
      'writing into the file
      Try
          bw.Write(i)
          bw.Write(d)
          bw.Write(b)
          bw.Write(s)
      Catch e As IOException
          Console.WriteLine(e.Message + "\n Cannot write to file.")
          Return
      End Try
      bw.Close()
      'reading from the file
      Try
          br = New BinaryReader(New FileStream("mydata", FileMode.Open))
      Catch e As IOException
          Console.WriteLine(e.Message + "\n Cannot open file.")
          Return
      End Try
      Try
           i = br.ReadInt32()
          Console.WriteLine("Integer data: {0}", i)
          d = br.ReadDouble()
          Console.WriteLine("Double data: {0}", d)
          b = br.ReadBoolean()
          Console.WriteLine("Boolean data: {0}", b)
          s = br.ReadString()
          Console.WriteLine("String data: {0}", s)
      Catch e As IOException
          Console.WriteLine(e.Message + "\n Cannot read from file.")
          Return
      End Try
      br.Close()
      Console.ReadKey()
   End Sub
End Module
When the above code is compiled and executed, it produces following result:
Integer data: 25
Double data: 3.14157
Boolean data: True
String data: I am happy

VB.Net allows you to work with the directories and files using various directory and file related classes like, theDirectoryInfo class and the FileInfo class.

The DirectoryInfo Class

The DirectoryInfo class is derived from the FileSystemInfo class. It has various methods for creating, moving, and browsing through directories and subdirectories. This class cannot be inherited.
Following are some commonly used properties of the DirectoryInfo class:
S.NProperty Name & Description
1Attributes
Gets the attributes for the current file or directory.
2CreationTime
Gets the creation time of the current file or directory.
3Exists
Gets a Boolean value indicating whether the directory exists.
4Extension
Gets the string representing the file extension.
5FullName
Gets the full path of the directory or file.
6LastAccessTime
Gets the time the current file or directory was last accessed.
7Name
Gets the name of this DirectoryInfo instance.
Following are some commonly used methods of the DirectoryInfo class:
S.NMethod Name & Purpose
1Public Sub Create
Creates a directory.
2Public Function CreateSubdirectory ( path As String ) As DirectoryInfo 
Creates a subdirectory or subdirectories on the specified path. The specified path can be relative to this instance of the DirectoryInfo class.
3Public Overrides Sub Delete
Deletes this DirectoryInfo if it is empty.
4Public Function GetDirectories As DirectoryInfo()
Returns the subdirectories of the current directory.
5Public Function GetFiles As FileInfo()
Returns a file list from the current directory.
For complete list of properties and methods please visit Microsoft's documentation.

The FileInfo Class

The FileInfo class is derived from the FileSystemInfo class. It has properties and instance methods for creating, copying, deleting, moving, and opening of files, and helps in the creation of FileStream objects. This class cannot be inherited.
Following are some commonly used properties of the FileInfo class:
S.NProperty Name & Description
1Attributes
Gets the attributes for the current file.
2CreationTime
Gets the creation time of the current file.
3Directory
Gets an instance of the directory which the file belongs to.
4Exists
Gets a Boolean value indicating whether the file exists.
5Extension
Gets the string representing the file extension.
6FullName
Gets the full path of the file.
7LastAccessTime
Gets the time the current file was last accessed.
8LastWriteTime
Gets the time of the last written activity of the file.
9Length
Gets the size, in bytes, of the current file.
10Name
Gets the name of the file.
Following are some commonly used methods of the FileInfo class:
S.NMethod Name & Purpose
1Public Function AppendText As StreamWriter
Creates a StreamWriter that appends text to the file represented by this instance of the FileInfo.
2Public Function Create As FileStream
Creates a file.
3Public Overrides Sub Delete
Deletes a file permanently.
4Public Sub MoveTo ( destFileName As String ) 
Moves a specified file to a new location, providing the option to specify a new file name.
5Public Function Open ( mode As FileMode ) As FileStream 
Opens a file in the specified mode.
6Public Function Open ( mode As FileMode, access As FileAccess ) As FileStream 
Opens a file in the specified mode with read, write, or read/write access.
7Public Function Open ( mode As FileMode, access As FileAccess, share As FileShare ) As FileStream 
Opens a file in the specified mode with read, write, or read/write access and the specified sharing option.
8Public Function OpenRead As FileStream
Creates a read-only FileStream
9Public Function OpenWrite As FileStream
Creates a write-only FileStream.
For complete list of properties and methods, please visit Microsoft's documentation

Example

The following example demonstrates the use of the above mentioned classes:
Imports System.IO
Module fileProg
   Sub Main()
      'creating a DirectoryInfo object
      Dim mydir As DirectoryInfo = New DirectoryInfo("c:\Windows")
      ' getting the files in the directory, their names and size
      Dim f As FileInfo() = mydir.GetFiles()
      Dim file As FileInfo
      For Each file In f
          Console.WriteLine("File Name: {0} Size: {1}  ", file.Name, file.Length)
      Next file
      Console.ReadKey()
   End Sub
End Module
An object is a type of user interface element you create on a Visual Basic form by using a toolbox control. In fact, in Visual Basic, the form itself is also an object. Every Visual Basic control consists of three important elements:
  • Properties which describe the object,
  • Methods cause an object to do something and
  • Events are what happens when an object does something.

Control Properties

All the Visual Basic Objects can be moved, resized or customized by setting their properties. A property is a value or characteristic held by a Visual Basic object, such as Caption or Fore Color.
Properties can be set at design time by using the Properties window or at run time by using statements in the program code.
Object. Property = Value
Where
  • Object is the name of the object you're customizing.
  • Property is the characteristic you want to change.
  • Value is the new property setting.
For example,
Form1.Caption = "Hello"
You can set any of the form properties using Properties Windows. Most of the properties can be set or read during application execution. You can refer to Microsoft documentation for a complete list of properties associated with different controls and restrictions applied to them.

Control Methods

A method is a procedure created as a member of a class and they cause an object to do something. Methods are used to access or manipulate the characteristics of an object or a variable. There are mainly two categories of methods you will use in your classes:
  • If you are using a control such as one of those provided by the Toolbox, you can call any of its public methods. The requirements of such a method depend on the class being used
  • If none of the existing methods can perform your desired task, you can add a method to a class.
For example, the MessageBox control has a method named Show, which is called in the code snippet below:
Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) 
 Handles Button1.Click
        MessageBox.Show("Hello, World")
    End Sub
End Class

Control Events

An event is a signal that informs an application that something important has occurred. For example, when a user clicks a control on a form, the form can raise a Click event and call a procedure that handles the event. There are various types of events associated with a Form like click, double click, close, load , resize etc.
Following is the default structure of a form Load event handler subroutine. You can see this code by double clicking the code which will give you a complete list of the all events associated with Form control:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
 'event handler code goes here
End Sub
Here Handles MyBase.Load indicates that Form1_Load() subroutine handles Load event. Similar way you can check stub code for click, double click If you want to initialize some variables like properties etc. then you will keep such code inside Form1_Load() subroutine. Here important point to note is the name of the event handler which is by default Form1_Load, but you can change this name based on your naming convention you use in your application programming.

Basic Controls

VB.Net provides a huge variety of controls that help you to create rich user interface. Functionalities of all these controls are defined in the respective control classes. The control classes are defined in theSystem.Windows.Forms namespace.
The following table lists some of the commonly used controls:
S.N.Widget & Description
1Forms The container for all the controls that make up the user interface
2TextBox It represents a Windows text box control.
3Label It represents a standard Windows label.
4Button It represents a Windows button control.
5ListBox It represents a Windows control to display a list of items.
6ComboBox It represents a Windows combo box control.
7RadioButton It enables the user to select a single option from a group of choices when paired with other RadioButton controls.
8CheckBox Represents a Windows CheckBox.
9PictureBox It represents a Windows picture box control for displaying an image.
10ProgressBar It represents a Windows progress bar control.
11ScrollBar It Implements the basic functionality of a scroll bar control.
12DateTimePicker It represents a Windows control that allows the user to select a date and a time and to display the date and time with a specified format.
13TreeView It displays a hierarchical collection of labeled items, each represented by a TreeNode.
14ListView It represents a Windows list view control, which displays a collection of items that can be displayed using one of four different views.
Let's start with creating a Window Forms Application by following the following steps in Microsoft Visual Studio:File -> New Project -> Windows Forms Applications
Finally select OK, Microsoft Visual Studio your project and displays following window with a default Form with a name Form1.
VB.Net Form
Visual Basic Form is the container for all the controls that make up the user interface. Every window you see in a running visual basic application is a form, thus the terms form and window describe the same entity. Visual Studio creates a default form for you when you create a Windows Forms Application.
Every form will have title bar on which the form's caption is displayed and there will be buttons to close, maximize and minimize the form shown below:
VB.Net Form Title Bar
If you click the icon on the top left corner, it opens the control menu, which contains the various commands to control the form like to move control from one place to another place, to maximize or minimize the form or to close the form.

Form Properties

Following table lists down various important properties related to a form. These properties can be set or read during application execution. You can refer to Microsoft documentation for a complete list of properties associated with a Form control:
S.NPropertiesDescription
1AcceptButtonThe button that's automatically activated when you press Enter, no matter which control has the focus at the time. Usually the OK button on a form is set as AcceptButton for a form.
2CancelButtonThe button that's automatically activated when you hit the Esc key. Usually the Cancel button on a form is set as CancelButton for a form.
3AutoScaleThis Boolean property determines whether the controls you place on the form are automatically scaled to the height of the current font. The default value of this property is True. This is a property of the form, but it affects the controls on the form.
4AutoScrollThis Boolean property indicates whether scroll bars will be automatically attached to the form if it is resized to a point that not all its controls are visible.
5AutoScrollMinSizeThis property lets you specify the minimum size of the form, before the scroll bars are attached.
6AutoScrollPositionThe AutoScrollPosition is the number of pixels by which the two scroll bars were displaced from their initial locations.
7BackColorSets the form background color.
8BorderStyleThe BorderStyle property determines the style of the form's border and the appearance of the form:
  • None: Borderless window that can't be resized.
  • Sizable: This is default value and will be used for resizable window that's used for displaying regular forms.
  • Fixed3D: Window with a visible border, "raised" relative to the main area. In this case windows can't be resized.
  • FixedDialog: A fixed window, used to create dialog boxes.
  • FixedSingle: A fixed window with a single line border.
  • FixedToolWindow: A fixed window with a Close button only. It looks like the toolbar displayed by the drawing and imaging applications.
  • SizableToolWindow: Same as the FixedToolWindow but resizable. In addition, its caption font is smaller than the usual.
9ControlBoxBy default this property is True and you can set it to False to hide the icon and disable the Control menu.
10EnabledIf True, allows the form to respond to mouse and keyboard events; if False, disables form.
11FontThis property specify font type, style, size
12HelpButtonDetermines whether a Help button should be displayed in the caption box of the form.
13HeightThis is the height of the Form in pixels.
14MinimizeBoxBy default this property is True and you can set it to False to hide the Minimize button on the title bar.
15MaximizeBoxBy default this property is True and you can set it to False to hide the Maximize button on the title bar.
16MinimumSizeThis specifies the minimum height and width of the window you can minimize.
17MaximumSizeThis specifies the maximum height and width of the window you maximize.
18NameThis is the actual name of the form.
19StartPositionThis property determines the initial position of the form when it's first displayed. It will have any of the following values:
  • CenterParent The form is centered in the area of its parent form.
  • CenterScreen The form is centered on the monitor.
  • Manual The location and size of the form will determine its starting position..
  • WindowsDefaultBounds The form is positioned at the default location and size determined by Windows.
  • WindowsDefaultLocation The form is positioned at the Windows default location and has the dimensions you've set at design time.
20TextThe text which will appear at the title bar of the form.
21Top, LeftThese two properties set or return the coordinates of the form's top-left corner in pixels.
22TopMostThis property is a True/False value that lets you specify whether the form will remain on top of all other forms in your application. Its default property is False.
23WidthThis is the width of the form in pixel.

Form Methods

The following are some of the commonly used methods of the Form class.You can refer to Microsoft documentation for a complete list of methods associated with forms control:
S.N.Method Name & Description
1Activate Activates the form and gives it focus.
2ActivateMdiChild Activates the MDI child of a form.
3AddOwnedForm  Adds an owned form to this form.
4BringToFront  Brings the control to the front of the z-order.
5CenterToParent  Centers the position of the form within the bounds of the parent form.
6CenterToScreen  Centers the form on the current screen.
7Close Closes the form.
8Contains  Retrieves a value indicating whether the specified control is a child of the control.
9Focus  Sets input focus to the control.
10Hide  Conceals the control from the user.
11Refresh Forces the control to invalidate its client area and immediately redraw itself and any child controls.
12Scale(SizeF)  Scales the control and all child controls by the specified scaling factor.
13ScaleControl  Scales the location, size, padding, and margin of a control.
14ScaleCore  Performs scaling of the form.
15Select  Activates the control.
16SendToBack  Sends the control to the back of the z-order.
17SetAutoScrollMargin Sets the size of the auto-scroll margins.
18SetDesktopBounds  Sets the bounds of the form in desktop coordinates.
19SetDesktopLocation  Sets the location of the form in desktop coordinates.
20SetDisplayRectLocation  Positions the display window to the specified value.
21Show  Displays the control to the user.
22ShowDialog  Shows the form as a modal dialog box.

Form Events

Following table lists down various important events related to a form. You can refer to Microsoft documentation for a complete list of events associated with forms control:
S.NEventDescription
1ActivatedOccurs when the form is activated in code or by the user.
2ClickOccurs when the form is clicked.
3ClosedOccurs before the form is closed.
4ClosingOccurs when the form is closing.
5DoubleClickOccurs when the form control is double-clicked.
6DragDropOccurs when a drag-and-drop operation is completed.
7EnterOccurs when the form is entered.
8GotFocusOccurs when the form control receives focus.
9HelpButtonClickedOccurs when the Help button is clicked.
10KeyDownOccurs when a key is pressed while the form has focus.
11KeyPressOccurs when a key is pressed while the form has focus.
12KeyUpOccurs when a key is released while the form has focus.
13LoadOccurs before a form is displayed for the first time.
14LostFocusOccurs when the form loses focus.
15MouseDownOccurs when the mouse pointer is over the form and a mouse button is pressed.
16MouseEnterOccurs when the mouse pointer enters the form.
17MouseHoverOccurs when the mouse pointer rests on the form.
18MouseLeaveOccurs when the mouse pointer leaves the form.
19MouseMoveOccurs when the mouse pointer is moved over the form.
20MouseUpOccurs when the mouse pointer is over the form and a mouse button is released.
21MouseWheelOccurs when the mouse wheel moves while the control has focus.
22MoveOccurs when the form is moved.
23ResizeOccurs when the control is resized.
24ScrollOccurs when the user or code scrolls through the client area.
25ShownOccurs whenever the form is first displayed.
26VisibleChangedOccurs when the Visible property value changes.

Example:

Following is an example which shows how we create two buttons at the time of form load event and different properties are being set at the same time.
Because Form1 is being referenced with-in its own event handler so it will be written as Me instead of using its name, but if we access the same form inside any other control's event handler then it will access using its nameForm1.
Let's double click on the Form and put the follow code in the opened window.
Public Class Form1

   Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
      ' Create two buttons to use as the accept and cancel buttons. 
      Dim button1 As New Button()
      Dim button2 As New Button()
      ' Set the text of button1 to "OK".
      button1.Text = "OK"
      ' Set the position of the button on the form.
      button1.Location = New Point(10, 10)
      ' Set the text of button2 to "Cancel".
      button2.Text = "Cancel"
      ' Set the position of the button based on the location of button1.
      button2.Location = _
         New Point(button1.Left, button1.Height + button1.Top + 10)
      ' Set the caption bar text of the form.   
      Me.Text = "tutorialspoint.com"
      ' Display a help button on the form.
      Me.HelpButton = True
     ' Define the border style of the form to a dialog box.
      Me.FormBorderStyle = FormBorderStyle.FixedDialog
      ' Set the MaximizeBox to false to remove the maximize box.
      Me.MaximizeBox = False
      ' Set the MinimizeBox to false to remove the minimize box.
      Me.MinimizeBox = False
      ' Set the accept button of the form to button1.
      Me.AcceptButton = button1
      ' Set the cancel button of the form to button2.
      Me.CancelButton = button2
      ' Set the start position of the form to the center of the screen.
      Me.StartPosition = FormStartPosition.CenterScreen
      ' Set window width and height
      Me.Height = 300
      Me.Width = 560
      ' Add button1 to the form.
      Me.Controls.Add(button1)
      ' Add button2 to the form.
      Me.Controls.Add(button2)
   End Sub
End Class
When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show following window:
Resulting Form

Text box controls allow entering text on a form at runtime. By default, it takes a single line of text, however, you can make it accept multiple texts and even add scroll bars to it.
Let's create a text box by dragging a Text Box control from the Toolbox and dropping it on the form.
VB.Net Text Box Control

The Properties of the TextBox Control

The following are some of the commonly used properties of the TextBox control:
S.NPropertyDescription
1AcceptsReturnGets or sets a value indicating whether pressing ENTER in a multiline TextBox control creates a new line of text in the control or activates the default button for the form.
2AutoCompleteCustomSourceGets or sets a custom System.Collections.Specialized.StringCollection to use when the AutoCompleteSourceproperty is set to CustomSource.
3AutoCompleteModeGets or sets an option that controls how automatic completion works for the TextBox.
4AutoCompleteSourceGets or sets a value specifying the source of complete strings used for automatic completion.
5CharacterCasingGets or sets whether the TextBox control modifies the case of characters as they are typed.
6FontGets or sets the font of the text displayed by the control.
7FontHeightGets or sets the height of the font of the control.
8ForeColorGets or sets the foreground color of the control.
9LinesGets or sets the lines of text in a text box control.
10MultilineGets or sets a value indicating whether this is a multiline TextBox control.
11PasswordCharGets or sets the character used to mask characters of a password in a single-line TextBox control.
12ReadOnlyGets or sets a value indicating whether text in the text box is read-only.
13ScrollBarsGets or sets which scroll bars should appear in a multiline TextBox control. This property has values:
  • None
  • Horizontal
  • Vertical
  • Both
14TabIndexGets or sets the tab order of the control within its container.
15TextGets or sets the current text in the TextBox.
16TextAlignGets or sets how text is aligned in a TextBox control. This property has values:
  • Left
  • Right
  • Center
17TextLengthGets the length of text in the control.
18WordWrapIndicates whether a multiline text box control automatically wraps words to the beginning of the next line when necessary.

The Methods of the TextBox Control

The following are some of the commonly used methods of the TextBox control:
S.NMethod Name & Description
1AppendText Appends text to the current text of a text box.
2Clear Clears all text from the text box control.
3Copy Copies the current selection in the text box to the Clipboard.
4Cut Moves the current selection in the text box to the Clipboard.
5Paste Replaces the current selection in the text box with the contents of the Clipboard.
6Paste(String) Sets the selected text to the specified text without clearing the undo buffer.
7ResetText Resets the Text property to its default value.
8ToString Returns a string that represents the TextBoxBase control.
9Undo Undoes the last edit operation in the text box.

Events of the TextBox Control

The following are some of the commonly used events of the Text control:
S.NEventDescription
1ClickOccurs when the control is clicked.
2DoubleClickOccurs when the control is double-clicked.
3TextAlignChangedOccurs when the TextAlign property value changes.

Example

In this example, we create three text boxes and use the Click event of a button to display the entered text using a message box. Take the following steps:
  1. Drag and drop three Label controls and three TextBox controls on the form.
  2. Change the texts on the labels to: Name, Organization and Comments respectively.
  3. Change the names of the text boxes to txtName, txtOrg and txtComment respectively.
  4. Drag and drop a button control on the form. Set its name to btnMessage and its text property to 'Send Message'.
  5. Click the button to add the Click event in the code window and add the following code.
Public Class Form1
   Private Sub Form1_Load(sender As Object, e As EventArgs) _
       Handles MyBase.Load
      ' Set the caption bar text of the form.  
      Me.Text = "tutorialspont.com"
   End Sub
    
   Private Sub btnMessage_Click(sender As Object, e As EventArgs) _
   Handles btnMessage.Click
      MessageBox.Show("Thank you " + txtName.Text + " from " + txtOrg.Text)
   End Sub
End Class
When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show following window:
Result Form
Clicking the Send Message button would show the following message box:
Result Form

The Label control represents a standard Windows label. It is generally used to display some informative text on the GUI, which is not changed during runtime.
Let's create a label by dragging a Label control from the Toolbox and dropping it on the form.
VB.Net Label Control

Properties of the Label Control

The following are some of the commonly used properties of the Label control:
S.NPropertyDescription
1AutosizeGets or sets a value specifying if the control should be automatically resized to display all its contents.
2BorderStyleGets or sets the border style for the control.
3FlatStyleGets or sets the flat style appearance of the Label control
4FontGets or sets the font of the text displayed by the control.
5FontHeightGets or sets the height of the font of the control.
6ForeColorGets or sets the foreground color of the control.
7PreferredHeightGets the preferred height of the control.
8PreferredWidthGets the preferred width of the control.
9TabStopGets or sets a value indicating whether the user can tab to the Label. This property is not used by this class.
10TextGets or sets the text associated with this control.
11TextAlignGets or sets the alignment of text in the label.

Methods of the Label Control

The following are some of the commonly used methods of the Label control:
S.NMethod Name & Description
1GetPreferredSize Retrieves the size of a rectangular area into which a control can be fitted.
2Refresh Forces the control to invalidate its client area and immediately redraw itself and any child controls.
3Select Activates the control.
4Show Displays the control to the user.
5ToString Returns a String that contains the name of the control.

Events of the Label Control

The following are some of the commonly used events of the Label control:
S.NEventDescription
1AutoSizeChangedOccurs when the value of the AutoSize property changes.
2ClickOccurs when the control is clicked.
3DoubleClickOccurs when the control is double-clicked.
4GotFocusOccurs when the control receives focus.
5LeaveOccurs when the input focus leaves the control.
6LostFocusOccurs when the control loses focus.
7TabIndexChangedOccurs when the TabIndex property value changes.
8TabStopChangedOccurs when the TabStop property changes.
9TextChangedOccurs when the Text property value changes.
Consult Microsoft documentation for detailed list of properties, methods and events of the Label control.

Example

Following is an example which shows how we create two labels. Let us create the first label from the designer view tab and set its properties from the properties window. We will use the Click and the DoubleClick events of the label to move the first label and change its text and create the second label and add it to the form respectively.
Take the following steps:
  1. Drag and drop a Label control on the form.
  2. Set the Text property to provide the caption "This is a Label Control".
  3. Set the Font property from the properties window.
  4. Click the label to add the Click event in the code window and add the following codes.
Public Class Form1

   Private Sub Form1_Load(sender As Object, e As EventArgs) _
            Handles MyBase.Load
      ' Create two buttons to use as the accept and cancel buttons. 
      ' Set window width and height
      Me.Height = 300
      Me.Width = 560

      ' Set the caption bar text of the form.  
      Me.Text = "tutorialspont.com"
      ' Display a help button on the form.
      Me.HelpButton = True
   End Sub

   Private Sub Label1_Click(sender As Object, e As EventArgs) _
            Handles Label1.Click
      Label1.Location = New Point(50, 50)
      Label1.Text = "You have just moved the label"
   End Sub
   Private Sub Label1_DoubleClick(sender As Object, e As EventArgs) 
       Handles Label1.DoubleClick
      Dim Label2 As New Label
      Label2.Text = "New Label"
      Label2.Location = New Point(Label1.Left, Label1.Height + _ 
   Label1.Top + 25)
      Me.Controls.Add(Label2)
   End Sub
End Class
When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show following window:
Result Form
Clicking and double clicking the label would produce the following effect:
Result Form

The Button control represents a standard Windows button. It is generally used to generate a Click event by providing a handler for the Click event.
Let's create a label by dragging a Button control from the Toolbox ad dropping it on the form.
VB.Net Button Control

Properties of the Button Control

The following are some of the commonly used properties of the Button control:
S.NPropertyDescription
1AutoSizeModeGets or sets the mode by which the Button automatically resizes itself.
2BackColorGets or sets the background color of the control.
3BackgroundImageGets or sets the background image displayed in the control.
4DialogResultGets or sets a value that is returned to the parent form when the button is clicked. This is used while creating dialog boxes.
5ForeColorGets or sets the foreground color of the control.
6ImageGets or sets the image that is displayed on a button control.
7LocationGets or sets the coordinates of the upper-left corner of the control relative to the upper-left corner of its container.
8TabIndexGets or sets the tab order of the control within its container.
9TextGets or sets the text associated with this control.

Methods of the Button Control

The following are some of the commonly used methods of the Button control:
S.NMethod Name & Description
1GetPreferredSize Retrieves the size of a rectangular area into which a control can be fitted.
2NotifyDefault Notifies the Button whether it is the default button so that it can adjust its appearance accordingly.
3Select Activates the control.
4ToString Returns a String containing the name of the Component, if any. This method should not be overridden.

Events of the Button Control

The following are some of the commonly used events of the Button control:
S.NEventDescription
1ClickOccurs when the control is clicked.
2DoubleClickOccurs when the user double-clicks the Button control.
3GotFocusOccurs when the control receives focus.
4TabIndexChangedOccurs when the TabIndex property value changes.
5TextChangedOccurs when the Text property value changes.
6ValidatedOccurs when the control is finished validating.
Consult Microsoft documentation for detailed list of properties, methods and events of the Button control.

Example

In the following example, we create three buttons. In this example, let us:
  • Set captions for the buttons
  • Set some image for the button
  • Handle the click events of each buttons
Take following steps:
  1. Drag and drop a Label control on the form.
  2. Set the Text property to provide the caption "Tutorials Point".
  3. Drag and drop three buttons on the form.
  4. Using the properties window, change the Name properties of the buttons to btnMoto, btnLogo and btnExit respectively.
  5. Using the properties window, change the Text properties of the buttons to Show Moto, Show Logo and Exit respectively.
  6. Drag and Drop another button, using the properties window, set its Image property and name it btnImage.
At this stage, the form looks like:
Click the form and add following code in the code editor:
Public Class Form1
   Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
      ' Set the caption bar text of the form.  
      Me.Text = "tutorialspont.com"
      btnImage.Visible = False
   End Sub
   Private Sub btnMoto_Click(sender As Object, e As EventArgs) Handles btnMoto.Click
      btnImage.Visible = False
      Label1.Text = "Simple Easy Learning"
   End Sub
   Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
      Application.Exit()
   End Sub
   Private Sub btnLogo_Click(sender As Object, e As EventArgs) Handles btnLogo.Click
      Label1.Visible = False
      btnImage.Visible = True
   End Sub
End Class
Clicking the first button, displays:
Result Window
Clicking the second button displays:
Result Window
Clicking the third button, exits the application.
The ListBox represents a Windows control to display a list of items to a user. A user can select an item from the list. It allows the programmer to add items at design time by using the properties window, or at the runtime.
Let's create a list box by dragging a ListBox control from the Toolbox and dropping it on the form.
VB.Net List Box
You can populate the list box items either from the properties window or at runtime. To add items to a ListBox, select the ListBox control and get to the properties window, for the properties of this control. Click the ellipses (...) button next to the Items property. This opens the String Collection Editor dialog box, where you can enter the values one at a line.

Properties of the ListBox Control

The following are some of the commonly used properties of the ListBox control:
S.NPropertyDescription
1AllowSelectionGets a value indicating whether the ListBox currently enables selection of list items.
2BorderStyleGets or sets the type of border drawn around the list box.
3ColumnWidthGets of sets the width of columns in a multicolumn list box.
4HorizontalExtentGets or sets the horizontal scrolling area of a list box.
5HorizontalScrollBarGets or sets the value indicating whether a horizontal scrollbar is displayed in the list box.
6ItemHeightGets or sets the height of an item in the list box.
7ItemsGets the items of the list box.
8MultiColumnGets or sets a value indicating whether the list box supports multiple columns.
9ScrollAlwaysVisibleGets or sets a value indicating whether the vertical scroll bar is shown at all times.
10SelectedIndexGets or sets the zero-based index of the currently selected item in a list box.
11SelectedIndicesGets a collection that contains the zero-based indexes of all currently selected items in the list box.
12SelectedItemGets or sets the currently selected item in the list box.
13SelectedItemsGets a collection containing the currently selected items in the list box.
14SelectedValueGets or sets the value of the member property specified by the ValueMember property.
15SelectionModeGets or sets the method in which items are selected in the list box. This property has values:
  • None
  • One
  • MultiSimple
  • MultiExtended
16SortedGets or sets a value indicating whether the items in the list box are sorted alphabetically.
17TextGets or searches for the text of the currently selected item in the list box.
18TopIndexGets or sets the index of the first visible item of a list box.

Methods of the ListBox Control

The following are some of the commonly used methods of the ListBox control:
S.NMethod Name & Description
1BeginUpdate Prevents the control from drawing until the EndUpdate method is called, while items are added to the ListBox one at a time.
2ClearSelected Unselects all items in the ListBox.
3EndUpdate Resumes drawing of a list box after it was turned off by the BeginUpdate method.
4FindString Finds the first item in the ListBox that starts with the string specified as an argument.
5FindStringExact Finds the first item in the ListBox that exactly matches the specified string.
6GetSelected Returns a value indicating whether the specified item is selected.
7SetSelected Selects or clears the selection for the specified item in a ListBox.
8OnSelectedIndexChanged Raises the SelectedIndexChanged event.
8OnSelectedValueChanged Raises the SelectedValueChanged event.

Events of the ListBox Control

The following are some of the commonly used events of the ListBox control:
S.NEventDescription
1ClickOccurs when a list box is selected.
2SelectedIndexChangedOccurs when the SelectedIndex property of a list box is changed.
Consult Microsoft documentation for detailed list of properties, methods and events of the ListBox control.

Example 1

In the following example, let us add a list box at design time and add items on it at runtime.
Take the following steps:
  1. Drag and drop two labels, a button and a ListBox control on the form.
  2. Set the Text property of the first label to provide the caption "Choose your favourite destination for higher studies".
  3. Set the Text property of the second label to provide the caption "Destination". The text on this label will change at runtime, when the user selects an item on the list.
  4. Click the listbox and the button controls to add the following codes in the code editor.
Public Class Form1
   Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
      ' Set the caption bar text of the form.  
      Me.Text = "tutorialspont.com"
      ListBox1.Items.Add("Canada")
      ListBox1.Items.Add("USA")
      ListBox1.Items.Add("UK")
      ListBox1.Items.Add("Japan")
      ListBox1.Items.Add("Russia")
      ListBox1.Items.Add("China")
      ListBox1.Items.Add("India")
   End Sub
  
   Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
      MsgBox("You have selected " + ListBox1.SelectedItem.ToString())
   End Sub
   Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) 
        Handles ListBox1.SelectedIndexChanged
      Label2.Text = ListBox1.SelectedItem.ToString()
   End Sub
End Class
When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show following window:
Result Form
When the user chooses a destination, the text in the second label changes:
Result Form
Clicking the Select button, displays a message box with the user's choice:
List Example Dialog Box

Example 2

In this example, we will fill up a list box with items, retrieve the total number of items in the list box, sort the list box, remove some items and clear the entire list box.
Design the Form:
List Box Example2
Add the following code in the code editor window:
Public Class Form1
   Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
      ' Set the caption bar text of the form.  
      Me.Text = "tutorialspont.com"
      ' creating multi-column and multiselect list box
      ListBox1.MultiColumn = True
      ListBox1.SelectionMode = SelectionMode.MultiExtended
   End Sub
   'populates the list
   Private Sub Button1_Click_1(sender As Object, e As EventArgs) _
          Handles Button1.Click
      ListBox1.Items.Add("Safety")
      ListBox1.Items.Add("Security")
      ListBox1.Items.Add("Governance")
      ListBox1.Items.Add("Good Music")
      ListBox1.Items.Add("Good Movies")
      ListBox1.Items.Add("Good Books")
      ListBox1.Items.Add("Education")
      ListBox1.Items.Add("Roads")
      ListBox1.Items.Add("Health")
      ListBox1.Items.Add("Food for all")
      ListBox1.Items.Add("Shelter for all")
      ListBox1.Items.Add("Industrialisation")
      ListBox1.Items.Add("Peace")
      ListBox1.Items.Add("Liberty")
      ListBox1.Items.Add("Freedom of Speech")
   End Sub
   'sorting the list
   Private Sub Button2_Click(sender As Object, e As EventArgs) _
          Handles Button2.Click
      ListBox1.Sorted = True
   End Sub
   'clears the list
   Private Sub Button3_Click(sender As Object, e As EventArgs) _
          Handles Button3.Click
      ListBox1.Items.Clear()
   End Sub
   'removing the selected item
   Private Sub Button4_Click(sender As Object, e As EventArgs) _
          Handles Button4.Click
      ListBox1.Items.Remove(ListBox1.SelectedItem.ToString)
   End Sub
   'counting the numer of items
   Private Sub Button5_Click(sender As Object, e As EventArgs) _
          Handles Button5.Click
      Label1.Text = ListBox1.Items.Count
   End Sub
   'displaying the selected item on the third label
   Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) _
           Handles ListBox1.SelectedIndexChanged
      Label3.Text = ListBox1.SelectedItem.ToString()
   End Sub
End Class
When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show following window:
Result Form List Box Example 2
Fill the list and check workings of other buttons:
Result Form List Box Example 2

The ComboBox control is used to display a drop-down list of various items. It is a combination of a text box in which the user enters an item and a drop-down list from which the user selects an item.
Let's create a combo box by dragging a ComboBox control from the Toolbox and dropping it on the form.
VB.Net ComboBox Control
You can populate the list box items either from the properties window or at runtime. To add items to a ListBox, select the ListBox control and get to the properties window, for the properties of this control. Click the ellipses (...) button next to the Items property. This opens the String Collection Editor dialog box, where you can enter the values one at a line.

Properties of the ComboBox Control

The following are some of the commonly used properties of the ComboBox control:
S.NPropertyDescription
1AllowSelectionGets a value indicating whether the list enables selection of list items.
2AutoCompleteCustomSourceGets or sets a custom System.Collections.Specialized.StringCollection to use when the AutoCompleteSourceproperty is set to CustomSource.
3AutoCompleteModeGets or sets an option that controls how automatic completion works for the ComboBox.
4AutoCompleteSourceGets or sets a value specifying the source of complete strings used for automatic completion.
5DataBindingsGets the data bindings for the control.
6DataManagerGets the CurrencyManager associated with this control.
7DataSourceGets or sets the data source for this ComboBox.
8DropDownHeightGets or sets the height in pixels of the drop-down portion of the ComboBox.
9DropDownStyleGets or sets a value specifying the style of the combo box.
10DropDownWidthGets or sets the width of the of the drop-down portion of a combo box.
11DroppedDownGets or sets a value indicating whether the combo box is displaying its drop-down portion.
12FlatStyleGets or sets the appearance of the ComboBox.
13ItemHeightGets or sets the height of an item in the combo box.
14ItemsGets an object representing the collection of the items contained in this ComboBox.
15MaxDropDownItemsGets or sets the maximum number of items to be displayed in the drop-down part of the combo box.
16MaxLengthGets or sets the maximum number of characters a user can enter in the editable area of the combo box.
17SelectedIndexGets or sets the index specifying the currently selected item.
18SelectedItemGets or sets currently selected item in the ComboBox.
19SelectedTextGets or sets the text that is selected in the editable portion of a ComboBox.
20SelectedValueGets or sets the value of the member property specified by the ValueMember property.
21SelectionLengthGets or sets the number of characters selected in the editable portion of the combo box.
22SelectionStartGets or sets the starting index of text selected in the combo box.
23SortedGets or sets a value indicating whether the items in the combo box are sorted.
24TextGets or sets the text associated with this control.

Methods of the ComboBox Control

The following are some of the commonly used methods of the ComboBox control:
S.NMethod Name & Description
1BeginUpdate Prevents the control from drawing until the EndUpdate method is called, while items are added to the combo box one at a time.
2EndUpdate Resumes drawing of a combo box, after it was turned off by the BeginUpdate method.
3FindString Finds the first item in the combo box that starts with the string specified as an argument.
4FindStringExact Finds the first item in the combo box that exactly matches the specified string.
5SelectAll Selects all the text in the editable area of the combo box.

Events of the ComboBox Control

The following are some of the commonly used events of the ComboBox control:
S.NEventDescription
1DropDownOccurs when the drop-down portion of a combo box is displayed.
2DropDownClosedOccurs when the drop-down portion of a combo box is no longer visible.
3DropDownStyleChangedOccurs when the DropDownStyle property of the ComboBox has changed.
4SelectedIndexChangedOccurs when the SelectedIndex property of a ComboBox control has changed.
5SelectionChangeCommittedOccurs when the selected item has changed and the change appears in the combo box.

Example

In this example, let us fill a combo box with various items, get the selected items in the combo box and show them in a list box and sort the items.
Drag and drop a combo box to store the items, a list box to display the selected items, four button controls to add to the list box with selected items, to fill the combo box, to sort the items and to clear the combo box list respectively.
Add a label control that would display the selected item.
Result Form
Add the following code in the code editor window:
Public Class Form1
   Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
      ' Set the caption bar text of the form.  
      Me.Text = "tutorialspont.com"
   End Sub
   'sends the selected items to the list box
   Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
      If ComboBox1.SelectedIndex > -1 Then
          Dim sindex As Integer
          sindex = ComboBox1.SelectedIndex
          Dim sitem As Object
          sitem = ComboBox1.SelectedItem
          ListBox1.Items.Add(sitem)
      End If
   End Sub
   'populates the list
   Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
      ComboBox1.Items.Clear()
      ComboBox1.Items.Add("Safety")
      ComboBox1.Items.Add("Security")
      ComboBox1.Items.Add("Governance")
      ComboBox1.Items.Add("Good Music")
      ComboBox1.Items.Add("Good Movies")
      ComboBox1.Items.Add("Good Books")
      ComboBox1.Items.Add("Education")
      ComboBox1.Items.Add("Roads")
      ComboBox1.Items.Add("Health")
      ComboBox1.Items.Add("Food for all")
      ComboBox1.Items.Add("Shelter for all")
      ComboBox1.Items.Add("Industrialisation")
      ComboBox1.Items.Add("Peace")
      ComboBox1.Items.Add("Liberty")
      ComboBox1.Items.Add("Freedom of Speech")
      ComboBox1.Text = "Select from..."
   End Sub
   'sorting the list
   Private Sub Button3_Click(sender As Object, e As EventArgs)
      ComboBox1.Sorted = True
   End Sub
   'clears the list
   Private Sub Button4_Click(sender As Object, e As EventArgs)
      ComboBox1.Items.Clear()
   End Sub
   'displaying the selected item on the label
   Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) _
     Handles ListBox1.SelectedIndexChanged
      Label1.Text = ComboBox1.SelectedItem.ToString()
   End Sub
End Class
When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show following window:
Result Form
Click on various buttons to check the actions performed by each:
Result Form

The ComboBox control is used to display a drop-down list of various items. It is a combination of a text box in which the user enters an item and a drop-down list from which the user selects an item.
Let's create a combo box by dragging a ComboBox control from the Toolbox and dropping it on the form.
VB.Net ComboBox Control
You can populate the list box items either from the properties window or at runtime. To add items to a ListBox, select the ListBox control and get to the properties window, for the properties of this control. Click the ellipses (...) button next to the Items property. This opens the String Collection Editor dialog box, where you can enter the values one at a line.

Properties of the ComboBox Control

The following are some of the commonly used properties of the ComboBox control:
S.NPropertyDescription
1AllowSelectionGets a value indicating whether the list enables selection of list items.
2AutoCompleteCustomSourceGets or sets a custom System.Collections.Specialized.StringCollection to use when the AutoCompleteSourceproperty is set to CustomSource.
3AutoCompleteModeGets or sets an option that controls how automatic completion works for the ComboBox.
4AutoCompleteSourceGets or sets a value specifying the source of complete strings used for automatic completion.
5DataBindingsGets the data bindings for the control.
6DataManagerGets the CurrencyManager associated with this control.
7DataSourceGets or sets the data source for this ComboBox.
8DropDownHeightGets or sets the height in pixels of the drop-down portion of the ComboBox.
9DropDownStyleGets or sets a value specifying the style of the combo box.
10DropDownWidthGets or sets the width of the of the drop-down portion of a combo box.
11DroppedDownGets or sets a value indicating whether the combo box is displaying its drop-down portion.
12FlatStyleGets or sets the appearance of the ComboBox.
13ItemHeightGets or sets the height of an item in the combo box.
14ItemsGets an object representing the collection of the items contained in this ComboBox.
15MaxDropDownItemsGets or sets the maximum number of items to be displayed in the drop-down part of the combo box.
16MaxLengthGets or sets the maximum number of characters a user can enter in the editable area of the combo box.
17SelectedIndexGets or sets the index specifying the currently selected item.
18SelectedItemGets or sets currently selected item in the ComboBox.
19SelectedTextGets or sets the text that is selected in the editable portion of a ComboBox.
20SelectedValueGets or sets the value of the member property specified by the ValueMember property.
21SelectionLengthGets or sets the number of characters selected in the editable portion of the combo box.
22SelectionStartGets or sets the starting index of text selected in the combo box.
23SortedGets or sets a value indicating whether the items in the combo box are sorted.
24TextGets or sets the text associated with this control.

Methods of the ComboBox Control

The following are some of the commonly used methods of the ComboBox control:
S.NMethod Name & Description
1BeginUpdate Prevents the control from drawing until the EndUpdate method is called, while items are added to the combo box one at a time.
2EndUpdate Resumes drawing of a combo box, after it was turned off by the BeginUpdate method.
3FindString Finds the first item in the combo box that starts with the string specified as an argument.
4FindStringExact Finds the first item in the combo box that exactly matches the specified string.
5SelectAll Selects all the text in the editable area of the combo box.

Events of the ComboBox Control

The following are some of the commonly used events of the ComboBox control:
S.NEventDescription
1DropDownOccurs when the drop-down portion of a combo box is displayed.
2DropDownClosedOccurs when the drop-down portion of a combo box is no longer visible.
3DropDownStyleChangedOccurs when the DropDownStyle property of the ComboBox has changed.
4SelectedIndexChangedOccurs when the SelectedIndex property of a ComboBox control has changed.
5SelectionChangeCommittedOccurs when the selected item has changed and the change appears in the combo box.

Example

In this example, let us fill a combo box with various items, get the selected items in the combo box and show them in a list box and sort the items.
Drag and drop a combo box to store the items, a list box to display the selected items, four button controls to add to the list box with selected items, to fill the combo box, to sort the items and to clear the combo box list respectively.
Add a label control that would display the selected item.
Result Form
Add the following code in the code editor window:
Public Class Form1
   Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
      ' Set the caption bar text of the form.  
      Me.Text = "tutorialspont.com"
   End Sub
   'sends the selected items to the list box
   Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
      If ComboBox1.SelectedIndex > -1 Then
          Dim sindex As Integer
          sindex = ComboBox1.SelectedIndex
          Dim sitem As Object
          sitem = ComboBox1.SelectedItem
          ListBox1.Items.Add(sitem)
      End If
   End Sub
   'populates the list
   Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
      ComboBox1.Items.Clear()
      ComboBox1.Items.Add("Safety")
      ComboBox1.Items.Add("Security")
      ComboBox1.Items.Add("Governance")
      ComboBox1.Items.Add("Good Music")
      ComboBox1.Items.Add("Good Movies")
      ComboBox1.Items.Add("Good Books")
      ComboBox1.Items.Add("Education")
      ComboBox1.Items.Add("Roads")
      ComboBox1.Items.Add("Health")
      ComboBox1.Items.Add("Food for all")
      ComboBox1.Items.Add("Shelter for all")
      ComboBox1.Items.Add("Industrialisation")
      ComboBox1.Items.Add("Peace")
      ComboBox1.Items.Add("Liberty")
      ComboBox1.Items.Add("Freedom of Speech")
      ComboBox1.Text = "Select from..."
   End Sub
   'sorting the list
   Private Sub Button3_Click(sender As Object, e As EventArgs)
      ComboBox1.Sorted = True
   End Sub
   'clears the list
   Private Sub Button4_Click(sender As Object, e As EventArgs)
      ComboBox1.Items.Clear()
   End Sub
   'displaying the selected item on the label
   Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) _
     Handles ListBox1.SelectedIndexChanged
      Label1.Text = ComboBox1.SelectedItem.ToString()
   End Sub
End Class
When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show following window:
Result Form
Click on various buttons to check the actions performed by each:
Result Form

The RadioButton control is used to provide a set of mutually exclusive options. The user can select one radio button in a group. If you need to place more than one group of radio buttons in the same form, you should place them in different container controls like a GroupBox control.
Let's create three radio buttons by dragging RadioButton controls from the Toolbox and dropping on the form.
VB.Net Radio Button
The Checked property of the radio button is used to set the state of a radio button. You can display text, image or both on radio button control. You can also change the appearance of the radio button control by using theAppearance property.

Properties of the RadioButton Control

The following are some of the commonly used properties of the RadioButton control:
S.NPropertyDescription
1AppearanceGets or sets a value determining the appearance of the radio button.
2AutoCheckGets or sets a value indicating whether the Checked value and the appearance of the control automatically change when the control is clicked.
3CheckAlignGets or sets the location of the check box portion of the radio button.
4CheckedGets or sets a value indicating whether the control is checked.
5TextGets or sets the caption for a radio button.
6TabStopGets or sets a value indicating whether a user can give focus to the RadioButton control using the TAB key.

Methods of the RadioButton Control

The following are some of the commonly used methods of the RadioButton control:
S.NMethod Name & Description
1PerformClick Generates a Click event for the control, simulating a click by a user.

Events of the RadioButton Control

The following are some of the commonly used events of the RadioButton control:
S.NEventDescription
1AppearanceChangedOccurs when the value of the Appearance property of the RadioButton control is changed.
2CheckedChangedOccurs when the value of the Checked property of the RadioButton control is changed.
Consult Microsoft documentation for detailed list of properties, methods and events of the RadioButton control.

Example

In the following example, let us create two groups of radio buttons and use their CheckedChanged events for changing the BackColor and ForeColor property of the form.
Radio Button Example Result Form
Let's double click on the radio buttons and put the follow code in the opened window.
Public Class Form1
   Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
      ' Set the caption bar text of the form.  
      Me.Text = "tutorialspont.com"
   End Sub

   Private Sub RadioButton1_CheckedChanged(sender As Object, _
       e As EventArgs) Handles RadioButton1.CheckedChanged
      Me.BackColor = Color.Red
   End Sub
   Private Sub RadioButton2_CheckedChanged(sender As Object, _
      e As EventArgs) Handles RadioButton2.CheckedChanged
      Me.BackColor = Color.Green
   End Sub
   Private Sub RadioButton3_CheckedChanged(sender As Object, _ 
      e As EventArgs) Handles RadioButton3.CheckedChanged
      Me.BackColor = Color.Blue
   End Sub
  
   Private Sub RadioButton4_CheckedChanged(sender As Object, _
      e As EventArgs) Handles RadioButton4.CheckedChanged
      Me.ForeColor = Color.Black
   End Sub
   Private Sub RadioButton5_CheckedChanged(sender As Object, _
       e As EventArgs) Handles RadioButton5.CheckedChanged
      Me.ForeColor = Color.White
   End Sub
   Private Sub RadioButton6_CheckedChanged(sender As Object, _
      e As EventArgs) Handles RadioButton6.CheckedChanged
      Me.ForeColor = Color.Red
   End Sub
End Class
When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show following window:
Result Form

The TreeView control is used to display hierarchical representations of items similar to the ways the files and folders are displayed in the left pane of the Windows Explorer. Each node may contain one or more child nodes.
Let's click on a TreeView control from the Toolbox and place it on the form.
VB.Net TreeView Control

Properties of the TreeView Control

The following are some of the commonly used properties of the TreeView control:
S.NPropertyDescription
1BackColorGets or sets the background color for the control.
2BackgroundImageGets or set the background image for the TreeView control.
3BackgroundImageLayoutGets or sets the layout of the background image for the TreeView control.
4BorderStyleGets or sets the border style of the tree view control.
5CheckBoxesGets or sets a value indicating whether check boxes are displayed next to the tree nodes in the tree view control.
6DataBindingsGets the data bindings for the control.
7FontGets or sets the font of the text displayed by the control.
8FontHeightGets or sets the height of the font of the control.
9ForeColorThe current foreground color for this control, which is the color the control uses to draw its text.
10ItemHeightGets or sets the height of each tree node in the tree view control.
11NodesGets the collection of tree nodes that are assigned to the tree view control.
12PathSeparatorGets or sets the delimiter string that the tree node path uses.
13RightToLeftLayoutGets or sets a value that indicates whether the TreeView should be laid out from right-to-left.
14ScrollableGets or sets a value indicating whether the tree view control displays scroll bars when they are needed.
15SelectedImageIndexGets or sets the image list index value of the image that is displayed when a tree node is selected.
16SelectedImageKeyGets or sets the key of the default image shown when a TreeNode is in a selected state.
17SelectedNodeGets or sets the tree node that is currently selected in the tree view control.
18ShowLinesGets or sets a value indicating whether lines are drawn between tree nodes in the tree view control.
19ShowNodeToolTipsGets or sets a value indicating ToolTips are shown when the mouse pointer hovers over a TreeNode.
20ShowPlusMinusGets or sets a value indicating whether plus-sign (+) and minus-sign (-) buttons are displayed next to tree nodes that contain child tree nodes.
21ShowRootLinesGets or sets a value indicating whether lines are drawn between the tree nodes that are at the root of the tree view.
22SortedGets or sets a value indicating whether the tree nodes in the tree view are sorted.
23StateImageListGets or sets the image list that is used to indicate the state of the TreeView and its nodes.
24TextGets or sets the text of the TreeView.
25TopNodeGets or sets the first fully-visible tree node in the tree view control.
26TreeViewNodeSorterGets or sets the implementation of IComparer to perform a custom sort of the TreeView nodes.
27VisibleCountGets the number of tree nodes that can be fully visible in the tree view control.

Methods of the TreeView Control

The following are some of the commonly used methods of the TreeView control:
S.NMethod Name & Description
1CollapseAll Collapses all the nodes including all child nodes in the tree view control.
2ExpandAll Expands all the nodes.
3GetNodeAt Gets the node at the specified location.
4GetNodeCount Gets the number of tree nodes.
5Sort  Sorts all the items in the tree view control.
6ToString  Returns a string containing the name of the control.

Events of the TreeView Control

The following are some of the commonly used events of the TreeView control:
S.NEventDescription
1AfterCheckOccurs after the tree node check box is checked.
2AfterCollapseOccurs after the tree node is collapsed.
3AfterExpandOccurs after the tree node is expanded.
4AfterSelectOccurs after the tree node is selected.
5BeforeCheckOccurs before the tree node check box is checked.
6BeforeCollapseOccurs before the tree node is collapsed.
7BeforeExpandOccurs before the tree node is expanded.
8BeforeLabelEditOccurs before the tree node label text is edited.
9BeforeSelectOccurs before the tree node is selected.
10ItemDragOccurs when the user begins dragging a node.
11NodeMouseClickOccurs when the user clicks a TreeNode with the mouse.
12NodeMouseDoubleClickOccurs when the user double-clicks a TreeNode with the mouse.
13NodeMouseHoverOccurs when the mouse hovers over a TreeNode.
14PaddingChangedOccurs when the value of the Padding property changes.
15PaintOccurs when the TreeView is drawn.
16RightToLeftLayoutChangedOccurs when the value of the RightToLeftLayout property changes.
17TextChangedOccurs when the Text property changes.

The TreeNode Class

The TreeNode class represents a node of a TreeView. Each node in a TreeView control is an object of the TreeNode class. To be able to use a TreeView control we need to have a look at some commonly used properties and methods of the TreeNode class.

Properties of the TreeNode Class

The following are some of the commonly used properties of the TreeNode class:
S.NPropertyDescription
1BackColorGets or sets the background color of the tree node.
2CheckedGets or sets a value indicating whether the tree node is in a checked state.
3ContextMenuGets the shortcut menu that is associated with this tree node.
4ContextMenuStripGets or sets the shortcut menu associated with this tree node.
5FirstNodeGets the first child tree node in the tree node collection.
6FullPathGets the path from the root tree node to the current tree node.
7IndexGets the position of the tree node in the tree node collection.
8IsEditingGets a value indicating whether the tree node is in an editable state.
9IsExpandedGets a value indicating whether the tree node is in the expanded state.
10IsSelectedGets a value indicating whether the tree node is in the selected state.
11IsVisibleGets a value indicating whether the tree node is visible or partially visible.
12LastNodeGets the last child tree node.
13LevelGets the zero-based depth of the tree node in the TreeView control.
14NameGets or sets the name of the tree node.
15NextNodeGets the next sibling tree node.
16NodesGets the collection of TreeNode objects assigned to the current tree node.
17ParentGets the parent tree node of the current tree node.
18PrevNodeGets the previous sibling tree node.
19PrevVisibleNodeGets the previous visible tree node.
20TagGets or sets the object that contains data about the tree node.
21TextGets or sets the text displayed in the label of the tree node.
22ToolTipTextGets or sets the text that appears when the mouse pointer hovers over a TreeNode.
23TreeViewGets the parent tree view that the tree node is assigned to.

Methods of the TreeNode Class

The following are some of the commonly used methods of the TreeNode class:
S.NMethod Name & Description
1Collapse Collapses the tree node.
2Expand Expands the tree node.
3ExpandAll Expands all the child tree nodes.
4GetNodeCount Returns the number of child tree nodes.
5Remove  Removes the current tree node from the tree view control.
6Toggle Toggles the tree node to either the expanded or collapsed state.
7ToString  Returns a string that represents the current object.

Example

In this example, let us create a tree view at runtime. Let's double click on the Form and put the follow code in the opened window.
Public Class Form1
   Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
      'create a new TreeView
      Dim TreeView1 As TreeView
      TreeView1 = New TreeView()
      TreeView1.Location = New Point(10, 10)
      TreeView1.Size = New Size(150, 150)
      Me.Controls.Add(TreeView1)
      TreeView1.Nodes.Clear()
      'Creating the root node
      Dim root = New TreeNode("Application")
      TreeView1.Nodes.Add(root)
      TreeView1.Nodes(0).Nodes.Add(New TreeNode("Project 1"))
      'Creating child nodes under the first child
      For loopindex As Integer = 1 To 4
          TreeView1.Nodes(0).Nodes(0).Nodes.Add(New  _
              TreeNode("Sub Project" & Str(loopindex)))
      Next loopindex
      ' creating child nodes under the root
      TreeView1.Nodes(0).Nodes.Add(New TreeNode("Project 6"))
      'creating child nodes under the created child node
      For loopindex As Integer = 1 To 3
          TreeView1.Nodes(0).Nodes(1).Nodes.Add(New  _
              TreeNode("Project File" & Str(loopindex)))
      Next loopindex
      ' Set the caption bar text of the form.  
      Me.Text = "tutorialspoint.com"
   End Sub
End Class
When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show following window:
Treeview Example
You can expand the nodes to see the child nodes:
TreeView Result

The ListView control is used to display a list of items. Along with the TreeView control, it allows you to create a Windows Explorer like interface.
Let's click on a ListView control from the Toolbox and place it on the form.
VB.Net ListView Control
The ListView control displays a list of items along with icons. The Item property of the ListView control allows you to add and remove items from it. The SelectedItem property contains a collection of the selected items. The MultiSelectproperty allows you to set select more than one item in the list view. The CheckBoxes property allows you to set check boxes next to the items.

Properties of the ListView Control

The following are some of the commonly used properties of the ListView control:
S.NPropertyDescription
1AlignmentGets or sets the alignment of items in the control.
2AutoArrangeGets or sets whether icons are automatically kept arranged.
3BackColorGets or sets the background color.
4CheckBoxesGets or sets a value indicating whether a check box appears next to each item in the control.
5CheckedIndicesGets the indexes of the currently checked items in the control.
6CheckedItemsGets the currently checked items in the control.
7ColumnsGets the collection of all column headers that appear in the control.
8GridLinesGets or sets a value indicating whether grid lines appear between the rows and columns containing the items and subitems in the control.
9HeaderStyleGets or sets the column header style.
10HideSelectionGets or sets a value indicating whether the selected item in the control remains highlighted when the control loses focus.
11HotTrackingGets or sets a value indicating whether the text of an item or subitem has the appearance of a hyperlink when the mouse pointer passes over it.
12HoverSelectionGets or sets a value indicating whether an item is automatically selected when the mouse pointer remains over the item for a few seconds.
13InsertionMarkGets an object used to indicate the expected drop location when an item is dragged within a ListView control.
14ItemsGets a collection containing all items in the control.
15LabelWrapGets or sets a value indicating whether item labels wrap when items are displayed in the control as icons.
16LargeImageListGets or sets the ImageList to use when displaying items as large icons in the control.
17MultiSelectGets or sets a value indicating whether multiple items can be selected.
18RightToLeftLayoutGets or sets a value indicating whether the control is laid out from right to left.
19ScrollableGets or sets a value indicating whether a scroll bar is added to the control when there is not enough room to display all items.
20SelectedIndicesGets the indexes of the selected items in the control.
21SelectedItemsGets the items that are selected in the control.
22ShowGroupsGets or sets a value indicating whether items are displayed in groups.
23ShowItemToolTipsGets or sets a value indicating whether ToolTips are shown for the ListViewItem objects contained in theListView.
24SmallImageListGets or sets the ImageList to use when displaying items as small icons in the control.
25SortingGets or sets the sort order for items in the control.
26StateImageListGets or sets the ImageList associated with application-defined states in the control.
27TopItemGets or sets the first visible item in the control.
28ViewGets or sets how items are displayed in the control. This property has the following values:
  • LargeIcon - displays large items with a large 32 x 32 pixels icon.
  • SmallIcon - displays items with a small 16 x 16 pixels icon
  • List - displays small icons always in one column
  • Details - displays items in multiple columns with column headers and fields
  • Tile - displays items as full-size icons with item labels and sub-item information.
29VirtualListSizeGets or sets the number of ListViewItem objects contained in the list when in virtual mode.
30VirtualModeGets or sets a value indicating whether you have provided your own data-management operations for the ListView control.

Methods of the ListView Control

The following are some of the commonly used methods of the ListView control:
S.NMethod Name & Description
1Clear  Removes all items from the ListView control.
1ToString  Returns a string containing the string representation of the control.

Events of the ListView Control

The following are some of the commonly used events of the ListView control:
S.NEventDescription
1ColumnClickOccurs when a column header is clicked.
2ItemCheckOccurs when an item in the control is checked or unchecked.
3SelectedIndexChangedOccurs when the selected index is changed.
4TextChangedOccurs when the Text property is changed.

Example

In this example, let us create a list view at runtime. Let's double click on the Form and put the follow code in the opened window.
Public Class Form1
   Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
      'create a new ListView
      Dim ListView1 As ListView
      ListView1 = New ListView()
      ListView1.Location = New Point(10, 10)
      ListView1.Size = New Size(150, 150)
      Me.Controls.Add(ListView1)
      'Creating the list items
      Dim ListItem1 As ListViewItem
      ListItem1 = ListView1.Items.Add("Item 1")
      Dim ListItem2 As ListViewItem
      ListItem2 = ListView1.Items.Add("Item 2")
      Dim ListItem3 As ListViewItem
      ListItem3 = ListView1.Items.Add("Item 3")
      Dim ListItem4 As ListViewItem
      ListItem4 = ListView1.Items.Add("Item 4")
      'set the view property
      ListView1.View = View.SmallIcon
      ' Set the caption bar text of the form.  
      Me.Text = "tutorialspoint.com"
   End Sub
End Class
When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show following window:
ListView Example