Go Back   Gaming Gutter


» Site Navigation
» Home
» FAQ
» Log in
User Name:

Password:

Not a member yet?
Register Now!
» Advertisement
» Recent Threads
Go to first new post Splat A Sloth
Today 06:05 PM
Last post by atticus
Today 07:57 PM
5 Replies, 21 Views
Go to first new post Buying Pets with...
Today 06:51 PM
by jsndin
Last post by jsndin
Today 07:56 PM
6 Replies, 10 Views
Go to first new post Dirty Neopts Images
12-29-2008 04:28 PM
by Immoral
Last post by atticus
Today 07:55 PM
51 Replies, 747 Views
Go to first new post Fewmitz's Blog is...
01-04-2009 03:42 PM
by Fewmitz
Last post by Fewmitz
Today 07:54 PM
18 Replies, 177 Views
Go to first new post Lots of WN Painted /...
Today 07:33 PM
by donovan
Last post by donovan
Today 07:52 PM
2 Replies, 3 Views
View Single Post

 Explaining all that is VB
Old 11-25-2007, 07:58 PM   #1 (permalink)
Fewmitz
Resident Psychopath

Male Fewmitz is online now


 
Fewmitz's Avatar
 
Join Date: Nov 2006
Location: fewmitz@live.com
Posts: 5,880
GPoints: 7,241
iTrader: 1 / 100%
Fewmitz Is a Lord of AwesomenessFewmitz Is a Lord of AwesomenessFewmitz Is a Lord of Awesomeness
Rep Power: 17
Explaining all that is VB

Fewmitz's incredibly amazing Visual Basic Reference Sheet!

Okay, so instead of making another guide to make a simple VB program, I have decided to go through a make a sort of "Visual Basic reference source" to cover a large majority of the things you'll be using. This will be covered based on Visual Basic 2008 Beta, so any differences between that and VB6 will be corrected upon discovery

This Tutorial will cover:

~The workings of VB Studio
~Several Basic objects
~Timers
~Variables
~Subs and Functions
~How to use a module
~If statements
~Operators
~Loops
~.ToString()
~Case Statements
~Arrays
~Strings, only a breif note

So first, lets start with the bare basics

The Basics

This you probably won't need to read, but I'll put it down anyway. Once you open Visual Studio and create a new project (using the button in the upper left hand corner), you'll see what looks like a blank form, and that's exactly what it is. This is called the Form Design view. Here you put buttons. text boxes, etc using the toolbox, which can be found in the view menu.

Double clicking the form will take you to the code window. This is where you actually type the code that makes the buttons or textboxes you create "work". Note the two combo boxes above where you type the code. This allows you to switch between objects and change how subs are called using a menu.

Next there are modules, which can be found and inserted under the project menu. A module is just something that contains a chunk of code that you're going to use over and over. It helps with organization of the program so the main form isn't so cluttered. These will only work if certain requirements are given, though. So for example, if you write a mod to display an array (which we'll get into later), you'll need to have an array passed into the function or else you'll get an error. In some tutorial in the future where I'll handle slightly more advanced stuff, I'll talk about Try...Catch...Finally statements to handle errors.

The only other worthwhile thing to mention here is the solution explorer, which is usually hiding on one of the sides. All this window does is allow you to switch between forms, modules, etc.

Continuing the Basics: The objects you'll use the most

I'm gonna make this section as short as possible because no one cares about this stuff, or at the very least it shouldn't have its own section.

When you put something from the toolbox onto the form in Design View, you've created an object. Double clicking this object will take you to the code window for that object. The form automatically selects a sub that will handle the event that would be most commonly used for that object. Below are some objects that you're going to use a lot and the default process for them:

Button: Click
Textbox: Text Changed
Label: Click
Form: Load (When it starts or opens)

etc etc. It's not unlikely that those are the only ones you're going to use.

Now, you can change these with one of two methods. First is going to the first like (Beginning with "Private Sub...") and changing the name from something like "Private Sub btn1_Click..." to "Private Sub btn1_MouseOver..." then doing the same thing to the similar statement at the end of that first line. It'll come after "Handles".

Second is the far easier method, just click somewhere in that first line, then go to the combo box above the code window (the one on the right) and change it. This will make a new Sub, so delete the old one (make sure to copy your code if you have any!).

As for what each of them do, most are self explanatory, but you'll need to experiment a little to figure out the differenced between things like "Key Down" and "Key Press"

Another useful little feature is the command ".focus()" This command will highlight the object. Ex: btn1.focus()

It's also important to note you can view the propertied of an object either on the right side of the window, or by right clicking it and selecting "properties"

Forms

I decided to make a little section for this because it has some unique properties and things like that.

First are the basic functions:

.show()
.close()
.hide()

They do exactly what they sound like, .show shows the form, .close() closes it, and .hide() hides it. The difference between close and hide is that hide does not close the form, just puts it out of sight (hides it...eh)

Remember, if you want to close the form you're on, use "Me.close()". This will work no matter what sub it's called in. So if you're in a button click and use "Me.Close()", the form will close the form, not the...button.

Timers

Also decided to make this because timers are a little unique.

The default sub routine called with a timer is via the command "tick". How many times the timer ticks is based on the interval property. In Visual Basic, 100 in the interval field = 1 second. This will vary from language to language, but this is a Visual Basic tut, after all ;p.

A property you'll be using a lot is the "enabled" property. If you set this to false, then you would enable the timer by putting this code in a button click or what have you:
Code:
timer1.enabled=True
Timers allow you to automate some functions at even times, you can also change the interval property in the code if need be.

Variables

Finally we get into actual coding.

Variables are containers that hold various types and values depending on what type it is.

There are several ways to declare a variable, so here we go:

Dim - Dimensions a variable. This is the most basic kind, if use this above all your code, then you can use it in any sub. If you use this command in, oh say, a button click, then that variable is only usable in that function
Static- Must be used in a specific sub. This variable will not lose its data. Example:
Code:
    Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim x As Integer
        Static y As Integer
        x = x + 1
        y = y + 1
    End Sub
In this example, we add one to x and y every time the form loads. The difference is that x will always be 1, because every time the form is loaded, x is redeclared as 0, and then one is added to it. The difference is that y does not lose its value every time the form is loaded.

Const: This variable will keep the value it was declared with. The value cannot change and as such will always be the same.
Private: This variable can only be used in this form
Public: This variable can be used by any of the forms/modules in the project.

Secondly, there are also various TYPES of variables:

Integer: A number, can be any whole number
Int16,32, or 64: This just limits how long the variable can be
Single: A number with a decimal
Double: A longer number with a decimal
String: Can be anything, numbers or letters, but since it's not a number, it cannot be added like a number*
Long: A long integer

*Difference between adding Integers and Strings:

Code:
    Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim x As Integer = 2
        Static y As Integer = 3
        Dim z As String = "a "
        Dim w As String = " b"
        x = x + y
        z = z + w
    End Sub
The end result of this function will be that x would be 5 while z would be "a b"

Subs and Functions

Syntax:

Code:
    Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim x As Integer
        Static y As Integer
        Dim z As String = "a "
        Dim w As String = " b"
        x = x + 1
        y = y + 1
        z = z + w
    End Sub

    Private Function doIt()
        Dim x As Integer
        Static y As Integer
        Dim z As String = "a "
        Dim w As String = " b"
        x = x + 1
        y = y + 1
        z = z + w
        Return (X)
    End Function
So far you've already seen and probably used functions and subs (sub routines). These essentially do the same thing, but the difference is that a function must return a value. So when you run it, some value will be spit out. This could be useful because you could set a variable equal to a function, to you always have that output:
Code:
Dim x as integer = doIt()
Code used by objects (via button clicks or what have you) are by default sub routines. But you can also make your own:
Code:
Private Sub goTime()
The same concept applies for functions.

Passing variables into Functions and Sub Routines

Another important thing to understand how to do is pass variables into functions. This clears up form clutter by making sure all your variables aren't declared up top. By passing them into functions allows you to only use variables for functions that need it.

There are also two ways to pass information into functions and sub routines:

ByVal- Passes in the variable
ByRef-Passes in the actual variable, so the value would be changed everywhere.

Run this code for further explanation:

Code:
    Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim x As Integer = 1
        Dim z As String = "a"
        doIt(x, z)
        MsgBox(x)
        MsgBox(z)
    End Sub

    Private Function doIt(ByVal x As Integer, ByRef z As String)
        x = 2
        z = "b"
        MsgBox(x)
        MsgBox(z)
        Return (x + z)
    End Function
You'll notice that when you call a function that has a variable passed in, the variables you're passing in will need to be in (), separated by a comma for multiples.

How to use a module

This will be fairly short, but it's important to make sure you understand.

First, once you make a mod, you'll need to make sure you include a function or sub routine, so if you had a mod that looks like this:

Code:
    Private Function doIt(ByVal x As Integer)
        MsgBox(x)
        Return (x)
    End Function
You would get an error. Remember the difference between Private and Public variables? The same concept applies to sub routines.

So how do you call it? If you had the correct version of the above function in your mod, and your mod was called mod1, you would call the function like this:

msgBox(mod1.doIt(variable)).

If statements

Probably the most useful statement you'll use. Syntax:

Code:
    Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim x As Integer = 1
        Dim z As String = "a"
        If x = 1 Then
            MsgBox("YES")
        ElseIf (x > 1) Then
            MsgBox("YESSSSS")
        Else
            MsgBox("...no?")
        End If
    End Sub
The basics: Begin with If, then conditions followed by the statements. You can put the condition in parenthesis or you could just write the condition. From that point you could end the statement with "End If". Or you could use ElseIf to check for another condition or Else to execute some command if the condition(s) is/are not true.

Run the code anc change the value of the variable to demonstrate the condition if need be.

Operators

Just a simple list.

Numeric Operators:

+
-
*
/
And then there are also :

Mod- Returns the remainder (4 mod 3)
\- Returns how many times the second number can go into the first number (8\3)

And then there are string operators:

& - and
<> - not equal to (can also be used for numbers)

Loops

A loop is some amount of code that will execute a number of times based on conditions given. It will be covered in parts.

For Loops

A for loop will execute a number of times that you set. Ex:

Code:
    Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim x As Integer
        For x = 0 To 10
            MsgBox(x)
        Next
    End Sub
This sub will show the numbers 0-10 in a box, one at a time.

Another important thing about For loops is Step. Here's an example:

Code:
 Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim x As Integer
        For x = 10 To 0 Step -1
            MsgBox(x)
        Next
    End Sub
Step decides in what order the loop will execute and by what. This sub will show the same thing as the other one, only backwards. If the step was negative 2, then the form would show every other number because the code is executed on the basis of subtracting 10.

While Loops

Can be any of these:
  • Do While ... Loop
  • Do ... Loop While
  • Do Until ... Loop
  • Do ... Loop Until
Ex:

Code:
    Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim x, j As Integer
        Dim sTable As String = ""
        Do While (j < 10)
            sTable = sTable & i * j & " "
            j = j + 1
        Loop
    End Sub
Code:
    Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim i As Int16 = 2
        Dim iNum As Boolean = True
        Dim bPrime As Boolean = True
        Do
            If iNum Mod i = 0 Then bPrime = False
            i = i + 1
        Loop Until bPrime = False Or i = iNum
    End Sub
Due to the wording, these particular loops are pretty self explanatory.

.ToString()

Just typing .ToString() will take a number, for example, and turn it into a string, but there are also specific ways you can turn it into a string:

Code:
        Console.WriteLine(MyDouble.ToString("c")
        Console.WriteLine(MyDouble.ToString("d")
        Console.WriteLine(MyDouble.ToString("e")
        Console.WriteLine(MyDouble.ToString("f")
        Console.WriteLine(MyDouble.ToString("g")
        Console.WriteLine(MyDouble.ToString("n")
        Console.WriteLine(MyDouble.ToString("p")
        Console.WriteLine(MyDouble.ToString("x")
And here's what each do, using the number

c- Currency
d- A decimal Number
e- Scientific Notation
f- A number with decimals
g- Converted to the most compact number, either scientific or decimal, depending on places
n- Number containing comma separators where needed
p- Percent
x- Hexidecimal, the case of the x determines the case of the hex ("X" = "ABC"; "x" = "abc")

Case Statements

A lot like If...Else, but used with more options. Ex:

Code:
Select Case iX
                   case 2 
                      messagebox.show("even")
                   case 3, 5
                      messagebox.show("odd")
                   case 6 to 10
                      messagebox.show("Between 6 and 10")
                   case Is > 10
                      messagebox.show("Greater than 10")
                   case Else
                      messagebox.show("No Clue")
                End Select
This variable is deciding the case of variable iX. So if iX= 2 then the message box would be even. Notice that "Is" needs to be used before a greater than or less than. In theory you could also do "Case Is = 2" instead of "Case 2", but it's really not worth it.

This could be/generally is used with Combo Boxes and the value selected in them.

Arrays

An Array is basically a list of information of the same type. This type must be declared initially, although values in the array can be decided later. Commands you're going to use a lot if you're using arrays:

.length(0) -> The lenght of the array
.GetUpperBound(0)-> The last element of the array

When passing an array into a function, it's no longer "ByVal x as [type]" but it's not "as array"

Single Dimension arrays

Like a list of data

The number of the length command and GetUpperBound command for a 1 Dimensional array will always be (0)

Declaring:

Dim sNames(4) as String
Dim sWords() as String = {"Hi", "bye", "3", "asdf", "VB"}

sNames is blank because no values were given to it.

Here it's important to note that when referencing a value in an array that arrays are 0 based, while there lengths are counted normally. This means that for sWords, it's length would be 5, but the data actually looks like:

sWords(0) -"Hi"
sWords(1) - "bye"
sWords(2)-"3"
sWords(3)-"asdf"
sWords(4)-"VB"

Assigning:

sNames(0) = "Hi"
sNames(1) = "bye"

So here the first element in the array would not be "Hi" and the second would be "bye"

Resizing:

redim sNames(10)

This will WIPE the array and change the number of elements from 4 to 10

If you wanted to keep the values, then use:

redim preserve sNames(10)

This will still resize the array, but now there will be 6 more blank spots.

It's important to note that For Loops are generally used to sort through arrays:

Code:
    Private Function doIt(ByVal x As Array)
        Dim i As Integer
        For i = 0 To x.GetUpperBound(0)
            x(i) = "YES!"
        Next
        Return (x)
    End Function
This will set every item in the array to "YES!"

2D and multidimensional arrays

A 2D array is like a table of Data
A 3D array is like a cube of Data, which you probably won't use
You can try to use a 4D array, but you might screw up the space time continuum and end up in 3rd Grade

Differences with .GetUpperBound and .GetLength for a 2D or multidimentional array will be explained after the example.

Declaring:

Dim sTable(2,1) as String
Dim sTable(,) as String = {{"r0c0", "r0c1"}, {"r1c0","r1c1"},{"r2c0","r2c1"}}

Same principal applies, this table is 3 by 2. Declared (rows,cols)

Assigning:

sTable(0,0) = "r0c0"
sTable(2,1) = "r2c1"

For Loops are still used to sort through them:

Code:
Private Sub Make2DArray(ByVal ArrayX As Array)
               Dim i, j As Int16
               Dim sList As String
               For i = 0 To ArrayX.GetLength(0) - 1
                  For j = 0 To ArrayX.GetUpperBound(1)
                     ArrayX(i,j) = i*j
                  Next             
               Next             
            End Sub
Code:
Private Sub Display2DArray(ByVal ArrayX As Array)
               Dim i, j As Int16
               Dim sList As String
               For i = 0 To ArrayX.GetLength(0) - 1
                  For j = 0 To ArrayX.GetUpperBound(1)
                     sList = sList & ArrayX(i,              j) & " "             
                  Next             
                  sList = sList & vbCrLf              
               Next             
               MessageBox.Show(sList)
            End Sub
This will make a multiplication table and then display is as a table.

Two important facts are used here. Instead of GetUpperBound, you can use GetLength-1. It's the same one, but it's still sound.

Also, when using .GetUpperBound(x) or .GetLength(x), the x references the position it's using. So if you have this array:

Dim x(2,4) as integer

And use this:

x.GetLength(0), you could get 3
x.GetLength(1) would give you 5

Strings

A String can be anything, any character whatsoever. Here are some important pre-defined string functions:

Chr(#)- Will give you the selected character.
Chr(33) -> ! etc etc, try it out
String.Length -> length
String.IndexOf("e")-> The first "e" in the string
String.IndexOf("e",5)-> The First "e" starting at position 5
String.Substring(4,5)-> The 5 Character substring starting at position 4
String.ToUpper-> The String in all upper case
String.Remove(4,11)-> Removing 11 characters starting at position 4
String.Replace("e","E")-> Replaces each e with E

~~~

And that's it. At some point I'll be writing another tutorial that covers some more advanced stuff, but that's it. Anything I did wrong, PM me and I'll fix it.

If I don't get rep for this I'm going to kill someone.
__________________
  Reply With Quote
 
Powered by vBadvanced CMPS v3.1.0

All times are GMT -7. The time now is 07:58 PM.


vBulletin skin developed by: eXtremepixels
vBCredits v1.4 Copyright ©2007 - 2008, PixelFX Studios
The contents of this webpage are copyright © 2006-2008 GamingGutter.com. All Rights Reserved.

Page generated in 0.19360399 seconds (100.00% PHP - 0% MySQL) with 17 queries