Visual Basic .NET/Introduction

From Wikiversity
Jump to navigation Jump to search

This lesson will describe the fundamental ideas behind Visual Basic .NET. This will include Data Types, Code Blocks, and Definitions of some key words as well as a project to implement this information.

Lesson[edit | edit source]

Data Types[edit | edit source]

One important distinction between Visual Basic prior to .NET and VB.NET is that data types were initially very flat. A variable that was a string was just a pointer to a memory address that held a series of characters in it. VB.NET changed this (actually the .NET Common Language Runtime did) so that a string variable is actually an object with its own methods, properties and so on (more on this later). Really you need to be aware of the most common data types and how they work.

String Text like data like "The quick brown fox" or "42".

Note that in programming "42" is not equal to 42 without conversion to a number datatype.

Sbyte Numeric Value 0-127 (128 values, signed (+/-) 8 bits long)
Byte Numeric Value 0-127 (128 values, unsigned (+) 8 bits long)
Int16 Short Numeric Value 0-32,767 (32,768 values, Signed (+/-) 16 bits long)
Int32 Integer Numeric Value 0-2,147,483,647 (2,147,483,648 values, Signed (+/-) 32 bits long)
Int64 Long Numeric Value 0-9,223,372,036,854,775,807 (Signed (+/-) 64 bits long)
UInt16 Numeric Value 0-32,767 (32,768 values, Unsigned (+/-) 16 bits long)
UInt32 Numeric Value 0-2,147,483,647 (2,147,483,648 values, Unsigned (+/-) 32 bits long)
UInt64 Numeric Value 0-9,223,372,036,854,775,807 (Unsigned (+/-) 64 bits long)
Single Numeric Floating Point Value 0-3.402823e38 (Unsigned (+/-) 32 bits)

Also can hold Positive/Negative zero, Pos/Neg Infinity, and Not a number (NaN)

Double Numeric Floating Point Value 0-1.79769313486232e308 (Unsigned (+/-) 64 bits)

Also can hold Positive/Negative zero, Pos/Neg Infinity, and Not a number (NaN)

Decimal Numeric Floating Point Value 0-79,228,162,514,264,337,593,543,950,335 (Unsigned (+/-) 96 bits long)
Date A date object representing a date and time.

12:00:00, January 1, 0001 A.D. (CE) through 23:59:59, December 31, 9999 A.D.

Measured in "Ticks". 1 Tick = 100 nanoseconds.

Boolean True or False. Thats all there is to it.

Try This[edit | edit source]

Type the following into the code window within a subroutine (Between Sub and End Sub)

Dim MyString as String = "Hello World"

Assuming you typed that rather than copy/pasted it you should see an Intellisense box with several entries in it. These are functions and properties of that instance of the String class. In Previous incarnations of VB, to get the length of a string (the number of characters in it) you would invoke a function called Strings.Len to get the length, something like

MyShort = Strings.Len(MyString)

Now each string is an object that has all of the functions that you would use to get information about it or modify it right there in it. So you will now have something like so:

MyShort = MyString.Length

This does not really save a whole lot of space, but it does make it easier to read.

Code Blocks[edit | edit source]

There are several different code blocks that you must be comfortable with before we start coding. These are the following:

  • Subroutine - One or more lines of code that may or may not take an argument (a value passed from another code block) that does not return a value.
    Private Sub btnHelloWorld_Click(ByVal sender As System.Object, _
                                    ByVal e As System.EventArgs) _
                                    Handles btnHelloWorld.Click
        MsgBox("Hello World!" & vbNewLine & "It is a bright new day!")
    End Sub
  • Function - One or more lines of code that may or may not take an argument that returns a value.
    Public Function TimesTwo(ByVal Multiplier As Integer) As Integer
        Return Multiplier * 2
    End Function
  • Enum - A code block that sets up an enumerated value list. Enums allow you to create listed items of a type so that you can keep track of them much easier when you code.
    Public Enum Months As SByte
        January = 1
        February = 2
        March = 3
        April = 4
        May = 5
        June = 6
        July = 7
        August = 8
        September = 9
        October = 10
        November = 11
        December = 12
        Undefined = 0
    End Enum

Scope[edit | edit source]

You probably noticed in the examples above the words Public and Private. These two, along with others determines scope of the Sub, Function or whatever. An item that is public may be seen from other Classes (each form is a class separated from other forms) and other projects. Private items may only be called from the class that it is in. If Private Function TimesTwo is in the Form1 class, and I have code that I want to be able to call it from the Form2 class, I will have to do one of two things, I can make a public sub in Form1 that calls the function for Form2 or I can use the Friend Scope to friend Form2. All other classes will still be unable to call the function, but Form2 will be able to. The IDE automatically sets event handlers (like the btnHelloWorld_Click procedure above) as Private. These procedures are the code that should be executed when a specific even happens to a control. All controls have them, and the Form itself does too. Click, DragDrop, KeyPress, etc, all help define how the control works. Since you typically do not want anyone's code directly executing one of these procedures from outside, they are set to Private.

Definitions[edit | edit source]

Class - A definition or template for an object. In this case think of a class as a list of properties that make the object up, and functions that allow the object to do something.


Public Class Car
    Private m_Name As String
    Private m_Color As String
    Private m_NumberDoors As SByte
    Private m_EngineSize As SByte
    Private m_DriveWheels As SByte
    Private m_Mileage As Long
    Public Sub New()

    End Sub
    Public Sub New(ByVal Name As String)
        Me.Name = Name
    End Sub
    Public Property Name() As String
            Return m_Name
        End Get
        Set(ByVal value As String)
            m_Name = value
        End Set
    End Property
    Public Property Color() As String
    Public Property NumberDoors() As SByte
    Public Property EngineSize() As SByte
    Public Property DriveWheels() As SByte
    Public Property Mileage() As Long
            Return m_Mileage
        End Get
        Set(ByVal value As Long)
            m_Mileage = value
        End Set
    End Property
    Public Function Drive(ByVal Miles As Long)
        Me.Mileage += Miles
        Return Mileage
    End Function
End Class

The above car class has a means by which you can describe it, as well as a function to let you add mileage to it other than by saying MyCar.Mileage += 15. Instead you can say MyCar.Drive(15) and 15 will be added to the mileage.

Exercise[edit | edit source]

Lets start a new Windows Forms Application project.

  1. Add the following controls to the form and position them as you see fit. Additionally use the Properties box to assign them the appropriate properties.
    1. Textbox
      1. Name = txtMyText
      2. BackColor = Light Red (Left Tab, Top Red Color)
    2. Button
      1. Name = btnCommit
      2. Text = OK!
  2. Double Click on the button, and the IDE will create the appropriate even handler for the Click event.
  3. Add the following inside.
        Dim strText As String = Me.txtMyText.Text
        If Me.txtMyText.Text = "" Then
            MsgBox("You did not enter any text.", MsgBoxStyle.Critical, "Whoops!")
            Me.txtMyText.Text = strText.ToUpper()
            Me.txtMyText.BackColor = Color.ForestGreen
        End If

The above code demonstrates a topic in the next lesson (logical control structures), as well as a few of the ideas from this lesson.

The Dim statement at the top declares (Dimensions) a new variable named strText and sets it equal to the text property of the txtMyText control on the form. The Dim statement doesn't have to assign a value (Or object reference). You can do that on a separate line, but I typically do so on the dimension line. Next you have the If...Else... statement which tests the value of the text property. If it is empty, then it tells you so with the MsgBox. If there is text in the textbox (after the Else statement) it sets all of the characters to their uppercase versions (using the string objects .ToUpper method), and sets the background color to forest green.

While this code is not terribly useful, similar code is used to show users that the value that they have typed does not match what the textbox is expecting. For instance, what if the textbox is for an IP address, and the user enters a MAC address instead. You could write code that would recognize that the value in the text box is not an IP and turn the background red and disable the commit button.

One last thought[edit | edit source]

I have not yet commented any code, but I will soon when the code starts gtting more complicated. Un-commented code will take extra time to decipher when you have come back to it several months down the road. "Why did I do it that way? What is this variable for? Why did I blah blah blah when I could have blah blah blehed?"

Comments can be any sized and are denoted by a preceeding apostrophe (single quote if you like). I often block off areas of code that take care of a specific set of property assignents or something.

            'The user put text in the text box.  Change it to upper 
            'case and set the background color to forest green

There are some third party programs that can help make nice looking comments, but the first step is to resolve to comment the code well. Additionally, the next version of VB.NET will have a feature to allow for XML based commenting with some automated IDE entered XML tagging and whatnot. Read about it here.