|
Visual Basic Tutorial
|
|
01-01-2010, 09:04 PM
Post: #1
|
|||
|
|||
|
Visual Basic Tutorial
Hello, throughout this post I will teach you the basics of Visual Basic (.NET). Before we start I would like to clear up some things.
I am not saying that everything in this tutorial is 100% correct, if it was I would probably be getting paid millions. I also would like to point out that this has no benefit to me, I know the language, you don't so if you find something that is wrong or isn't explained well don't get grumpy and rage at me, ask me to clarify it for you and I will do my best. This is only a beginners tutorial, you should not assume total knowledge of Visual Basic after reading this, it will give you enough information to be able to develop "decent" software whilst you continue to broaden your knowledge. Who am I? I am FreckleS. I have been developing software in Visual Basic for over 4 years and other languages like C/C++ for 3. This tutorial may only be posted on my chosen sites which are listed in credits, it may be linked to with credits to me. If you wish to post this on another site, ask me and chances are I will let you. There might well be a few details here and there and spelling mistakes etc wrong so please if I have made mistakes please pm me them and don't fill the thread with them, I will fix them asap. First off I am not going to show you how to install VB and create a new project and all that crap as you should be able to that before you start this tutorial. I will use Console Applications as it saves me a lot of time creating Forms and taking screenshots for you and all that crap. Lesson 1 - Good Ol' Hello World The code that most programmers start with, Hello World. The Hello World program is one of the most basic programs that can be created in any language. Even though it is extremely simple it still has a few key parts to it. Code: ' Lesson1 - Hello WorldOn the first line you see: Code: 'Lesson1 - Hello WorldComments are one of the most useful types of internal documentation that can be included in a program. Although in this example it would probably be not needed it is good to start good programming practices from your very first application. Line 3 is one of the most important parts of the program. Code: Sub Main()Line 4 is what makes your program actually "talk" Code: Console.WriteLine("Hello World")WriteLine and many other functions are member functions of the Class "Console". The Console Class has many properties which can be set through the say way as you just wrote a line to the console, Class.Function or Class.Property = whatever. Line 5 is just a line of code that makes a program pause and wait for the user to hit a key before exiting so that we can read the output. Code: Console.ReadLine()Line 6 you tell the compiler that it is the end of your sub routine. Lesson 2 - Variables Just like in math and algebra something that changes its value is called a variable, the same rule applies in programming. Variables are a key part of a program for any language and the same applies for Visual Basic. A variables value can be changed with the Assignment Operator (=), you will learn more about this in the coming lessons. A variable must have a name and data type before it can be used, this is called declaring. In Visual Basic you can declare variables by the following syntax. Code: Dim <name> As <type>Code: Dim myAge As IntegerNow that the variable has been declared we can set its value, get its value and use it for many other purposes. Remember the Assignment Operator (=)? Visual Basic is a language that has the same operator for testing equality and assigning values. Example. Code: myAge = 15Code: If myAge = 15 ThenNot only can you set the value of a variable you can get it and use it. Code: ' Lesson 2 - VariablesLine 6 is a demonstration on how to write a variables value to the console window. you might think "what the hell is {0}" this tells the compiler that console.writeline will take 2 arguments now, not just the message but it will take an object in an argument. It also says take the value of the object and place it here. Another way of writing this would be to join the values. Code: Console.WriteLine("I am " & myAge & " years old") ' Write myAge to the screenThe main datatypes are the following:
For an understanding of the datatypes read http://www.rentron.com/datatypes.htm Quick Note - Understanding Operators There are a few types of operators available to Visual Basic, as well as other languages, that make our lives easier. These include, mathematical, relational, logical and assignment operators. In Visual Basic unlike a few other languages it has the same Assignment Operator and the same Equality Operator which is a member of the Relational Operator family. They are both (=). I personally am not sure if I like this prefered to a language like C++ where the equality operator is (==). Relational Operators: Here is a quick list of the relational operators: Name, Operator, Sample, Evaluates Equals, =, 10 = 20, False Not Equals, <>, 10 <> 20, True Greater Than, >, 10 > 20, False Less Than, <, 10 < 20, True Greater Than or Equal to, >=, 10 >= 20, False Less Than or Equal to, <=, 10 <= 20, True Logical Operators: And, Or, Not, AndAlso, Xor, OrElse They work in the way in which you might expect. And: It is used to evaluate two expressions. If both are correct then it will return true if not it will return false. Or: It is used to evaluate two expressions. If either one is correct then it will return true, if neither are correct it will return false. Not: It is used to evaluate an expression. If the expression evaluates to false then it will return true. It is has much or less the same effect as <>. Mathematical Operators: Like you would expect in maths, plus (+), minus (-), multiplication (*), division (/) and modulus (Mod) You should be fairly comfortable with the mathematical operators except for perhaps modulus. A good example of the modulus operator would be to find if a number was even or not. Modulus returns the remainder of a division. So 10 Mod 2 = 0 because it is evenly divisible. Code: Module Module1You can review more about operators here: http://www.startvbdotnet.com/language/operators.aspx Lesson 3 - If/Else Statements The 3 Control Structures for any program as my software teacher keeps reminding me is Sequence, Selection and Repition. If/Else Statements fall into the Selection catagory of these structures. It is just like it sounds, it will select which path to take. Code will always follow Sequence, it is a control structure that will always be, code will always flow, one statement after the other. In some cases it will take a different path (selection) or it might go over the same path again (repeition). Obviously you can't always know what a user is going to enter into your program so you need to be able to handle this, if you don't you program will most likely crash or something else bad will happen. If/Else Statements are a great way of handling exceptions and keeping your program bug free. The only better way of handling exceptions would be Try/Catch Statement but we will look into that later. The Syntax for a If/Else Statement is. Code: If <Expression> ThenWe used a very basic If Statement in the last lesson, although the code was unfinished it should have given you an overview of the statement. Code: ' Lesson 3 - If/Else StatementsObviously this will write the message "I am 15 years old" because you have assigned the variable myAge to be 15. This is just a basic example of the statement. Next we will look at user input to help make this and other programs a bit more functional. Lesson 4 - User Input In most of your applications you are going to need user input to select something, change a setting or whatever. You can achieve this by using the Console Class again as we have been using all the way through this tutorial. We can use almost the exact same program from Lesson 3 or even Lesson 2 only with a minor change. When we assign the value of myAge we are not going to give it a value, but more we are going to give it a function to run which will return a value and assign it to myAge variable. The definition of the ReadLine function is: Code: Public Shared Function ReadLine() As StringBasically all that that says is that it calls the member function ReadLine of class Console (System.Console to be 100%) and then returns the next line of character entered. Our assignment of myAge should now look like. Code: myAge = Console.ReadLine()That been said you should be able to implement it into your previous programs, I will do it with Lesson 3 so that we can use If/Else statements and also it is good to practice as you will learn from doing. You should also print a message before recieving input, something like "Please enter my age: " or something like that. You can do this by the member function WriteLine of class Console (You should remember). Code: ' Lesson 4 - User InputLesson 5 - Functions/Sub Routines This and the next lesson, Variable Scope, go hand in hand with each other. Throughout these tutorials I am going to refer to Sub Routines and Functions as the same thing, which they basically are, I do this because of my obession with C++ and other languages (foolish me...) The really only difference is that a function returns a value, there are a couple of minor differences but nothing you need to worry about in these tutorials. Oh and of course the other difference. The keywords are different. Keywords are words that are set aside by the compiler to be "special". You can't use these words in declarations etc, you can't name an integer variable like. Code: Dim integer As IntegerAnyway... Functions are the building blocks of programs, commercial software will have a huge number of functions in it. Functions allow you to split your program into parts which makes your program much easier to maintain for other programmers who might come into contact with your code. In Visual Basic unlike in other languages like C++ you don't need a function prototype before using your function. You can declare the function by using the following syntax. Code: Function <Name>(Arguments) As <Type>You should always take care when naming your functions. A function should only do one task and it should be named according to that task. An example is the Doubler function. It takes a number as an argument then it returns the value twice the number passed to it. Code: ' Lesson 5 - Functions/Sub RoutinesTo call a function you don't need to write the value to the screen, you can just call it like so. Code: <Name>(<arguments>)A sub routine can be used in much the same way except you change Function to Sub. Lesson 6 - Variable Scope Variable Scope is an important part for variables, especially when you start using multiple functions. Variable Scope is a problem that many new programmers come into contact with. I often see on forums people posting a compile error like <Variable> is not declared, even when it is. This is because the function that they are trying to access the variable from doesn't have permissions. This means that if you declare a variable within another function it will not be accessable in others. Try this program and you will understand. Code: ' Lesson 6 - Variable ScopeYou should recieve the following error. Error 1 Name 'myAge' is not declared. C:\Documents and Settings\FreckleS\Local Settings\Application Data\Temporary Projects\Lesson6\Module1.vb 9 16 Lesson6 This is because the variable is declared with the function Main(). In order to use the variable in DoubleAge() function you would need to pass it as a argument or parameter or you can declare the function outside of any other function which makes it available to any function. I will demonstrate both options. Code: ' Lesson 6 - Variable Scopeand Code: ' Lesson 6 - Variable ScopeIn the second example DoubleAge still doesn't know about myAge, all it knows is that its value (15) is passed to it as the num argument. Lesson 7 - Select Case Statements Remember the 3 control structures, Sequence, Selection, Repetition? Well these is If/Else statement's big brother. He can handle multiple selections with ease, much like if/else if/else. Although this can become cubersome with a large amount of selections, select case however...never The syntax for a Select Case Statement Code: Select Case <Expression>In my example I am just lazy so I didn't do all the options but you get the idea. Code: ' Lesson 7 - Select Case StatementsOn Line 7 it sets up the statement. This would be the same as writing Code: ' Lesson 7 - Select Case StatementsEven whilst I was writing that, small amount of selection I got bored with the if/else statements much before the select case statements. Lesson 8 - Arrays Arrays are a wonderful, powerful and mighty feature of Visual Basic. They allow you to store related information within the "same" variable. They are declared almost the same as a variable except that after the name you place brackets and the number of elements it can hold. In Visual Basic arrays are "Zero Based" which means the index starts at 0 so: Code: Dim customerNames(4) As StringTo assign an individual array you once again use almost the same syntax as for a variable. Code: customerNames(0) = "John Reed"The following code is quite cubersome and you will learn how to improve on this method shortly. Code: ' Lesson 8 - ArraysLesson 9 - Recursion & Loops The final control structure, Repetition. Repetition is a great feature of any programming language, it allows for things to do be done, a set number of times or an infinite number of times, however you should try to avoid this as it generally strains the CPU. There a few different types of loops.
Also in functions you can call the function from the same function which is called Recursion. A very basic loop is one that counts to 10. First you will need to declare a variable called "counter" as an integer. We will use either a Do Until or a Do While Loop, they achieve the same thing but have a slight difference in the expression. The syntax for a loop is generally. [code[ Do Until <Expression> <Statements> Loop [/code] We will use a counter integer as the test expression. This basically sets our number of loops. Code: ' Lesson 9 - Recursion & LoopsThis should give the output. 1 2 3 4 5 6 7 8 9 10 Wonderful...Why doesn't it print out 11 though you ask. Well...The loop tells us. Code: Do Until counter = 11Until is the keyword there. Once it is equal to 11 it will not loop again and go to the next line of code after the loop. Similiarly. Do While loops work in much the same manner. Code: ' Lesson 9 - Recursion & LoopsThat strange operator you see there "<>" is the not equals operator, or the Inequality Operator. Then you also all your normal maths crap, > greater than, < less than, >= greater than or equals to, <= less that or equals to. For Each...Next Loops as a wonderful loop that can be used to loop through something for a finite amount of times. Using an array is the perfect example so from the previous lesson. Code: ' Lesson 9 - Recursion & LoopsLesson 10 - Classes Classes are the building blocks to Object Orientated Programming (OOP). OOP is one of the main benefits of languages like Visual Basic and C++ over C and other languages. C is a structured language. OOP allows you to think about real world objects as if they were part of your computer. The world is filled with objects, cars, cats, dogs, trees, houses etc. These objects have characteristics, tall, brown, small, bark. OOP allows you to "import" these objects into your computer to manipulate. If you are looking for more information on OOP look up some C++ stuff. C++ was designed a bridge between C and OOP to bring the power of OOP to the commercial developer platform of C so there is plenty of resources about. Declaring a class is much like declaring a function or even a variable. It can also contain both of these. The syntax for declaring a class is. Class <Name> <Variables> <Functions> End Class I am going to use a Cat as an example. Code: Class CatThat is your class declared but now we want to use it. We need to create an object to be able to use it. In Main or whatever function you are in you can declare your object like so. Code: Dim <Object> As New CatCode: Dim Jasper As New Cat ' Create a new object instance of Cat named JasperNow you have a "working" Cat. To use the cat you can simply use the Object name followed by a period (.) then the member variable or member function or whatever. Code: ' Lesson 10 - ClassesBelieve it or not but you have been using OOP code since you started with that very first application, Hello World. When I mentioned member function of class with Console.ReadLine that is the exact same as this. Ours: Class = Cat Member Function = Meow Systems: Class = Console Member Function = ReadLine Amazing isn't it? Lesson 11 - File Manipulation File Manipulation is a very important part of programming, for me anyway. I like to often read values from text files and store data in them if I don't want to use registry or settings (don't worry). This Lesson is sort of a challenge. It will be short and sweet and as it is really a combination of some of the previous lessons hopefully you will be able to pick it up really easy. We need to import System.IO however which you may not have done before. This allows us to use code from the System.IO file. At the top of your workspace simply type. Code: Imports System.IONow we can use may features from the System.IO dll. One of which is StreamReader and its brother StreamWriter. You guessed it, this allows us to read and write bytes with a certain encryption to a file of our choice. You need to create an object of the StreamReader class and then we need to read the file so check out the member function ReadToEnd(). The code I came up with is. Code: ' Lesson 11 - File ManipulationHopefully you got something very similiar if not better and hopefully you got it easily. A couple of attempts and you should have it perfect. Make sure that you close the file or you will get errors next time you try to use it. Lesson 12 - Try Catch Statements I somewhat forgot about this but its ok cause its back now. It wasn't really needed too bad previously but it would have done good in the previous example. The Try...Catch Statement is used catch exceptions that may occur whilst you are trying to do something. Usually something with a high chance of failing. If I was to use the same sort of thing on the previous example it would like this. Code: ' Lesson 12 - Try Catch StatementsDelete the file "C:\Testfile.txt" and see what happens. You get this ugly long exception message. Since this is one of the most likely exceptions that occur we can count on that and make the handling a bit smoother, more user friendly. Code: ' Lesson 12 - Try Catch StatementsLesson 13 - Data Type Conversion Sometimes you might need data as a specific data type. Somebody might try to be smart and enter a double when you ask for an integer or something like that. In Visual Basic there are two types of Data Type Conversion, Implicity and Explicity. Implicity means that you do the conversion yourself. You don't actually convert but you store a value as the "wrong" data type and it will lose data. An example. Code: ' Lesson 13 - Data Type ConversionSince an Integer data type is a whole number the output will be 16. The compiler will round doub up. Explicity means that the data will automatically be converted. Visual Basic comes with a class called CType. It is a cast and the above example would like this this. Code: ' Lesson 13 - Data Type ConversionOr we could also use CInt which is the cast type of int. Code: ' Lesson 13 - Data Type ConversionOther data type conversion functions in Visual Basic include: Function, Use CBool, Convert to Boolean Data Type CByte, Convert to Byte Data Type CDate, Convert to Date Data Type CSng, Convert to Single Data Type CShort, Convert to Short Data Type CInt, Convert to Integer Data Type CLng, Convert to Long Data Type CDbl, Convert to Double Data Type CDec, Convert to Decimal Data Type CObj, Convert to Object Data Type CString, Convert to String Data Type CChar, Convert to Char Data Type Lesson 14 - Enumeration Enumeration is the use of a related set of constants, it is similiar to Classes but not quite as cool. The problem with enumeration is that you are working with constants, this is of course good in some instances but I prefer to work with classes, do as you wish. Fine...Ill teach you both. ![]() You can declare an enumerated type with the following syntax. Code: Enum <Name>Then the same as classes you can reference your constants with the Enum name followed by a period (.) then the constant. Code: ' Lesson 14 - EnumerationLesson 15 - Multithreading Multithreading is one of the most important parts of software developement. For me anyway. A lot of software is going to need to be able to do several things at once or a couple of high CPU or time consuming tasks at the same time. If your application is running on a single thread and you want to do a couple of these tasks at once then your program will lag. I will use the example of downloading a file from my website. First you must import the .dll System.Threading. So at the very top of your page: Code: Import System.ThreadingYou also must create a new function that will contain your code to download the file, or whatever it is you are making. Now as you should know by now, we can now use its member functions of the System.Threading Class. But as again you should know by now we have to create an object instance of it so we can use it. Code: Dim myThread As New Thread(AddressOf DownloadFile)A member function of the Thread class is Start. What do you think that does? Use it when you want to use your function. Code: ' Lesson 15 - MultithreadingYou should also remember to use the member function Abort() when you are finished with your thread as it will give the CPU a break. A couple more member functions of the Thread Class include:
You can also set the priority of threads just like you can to processes in Task Manager. Priority = ThreadPriority.Highest The list of priorities include:
I think your done. Now here is some useful code snippets that you can use just give credits to me. Custom CopyFile Class Code: Imports System.IORecursive File Search Code: Imports System.IOBasic Anti-Leak Protection Code: Imports System.ManagementYeah thats enough code, you can also learn a bit by studying these codes. By reading ALL of this doesn't make you a Visual Basic programmer, it gives you a good step into the language however. There are thousands of resources out there and in time you will become better and better just keep practicing and coding. The best way to learn is by doing. Credits:
This tutorial may not be distributed without my permission, ask me if you would like to and chances are I will let you. Do the right thing by me and I will return the favour. If people find that I have done something wrong please let me know, I am not perfect and this has really taken it out of me. I know that I haven't explained everything perfectly and if you would clarification ask. Or contact me at: Email: freckles@abclan.net or codeducks@gmail.com MSN: freckles@muppetalert.com Xfire: freckles123 Steam: Code_Ducks PM: At any of the above listed sites. Have fun! Source Codes Attached to Thread
|
|||
|
01-01-2010, 09:30 PM
Post: #2
|
|||
|
|||
|
RE: Visual Basic Tutorial
This is amazingly good and amazingly big. You took everything into consideration, and i appreciate that !
Loads of example is also good. BTW Good to see someone who knows what recursion is. All together great work ! There's a fine line between genius and insanity. I have erased this line. Oscar Levant There's a fine line between an administrator and black hat hacker. I have erased this line. Dr DEBCOL |
|||
|
01-01-2010, 09:36 PM
Post: #3
|
|||
|
|||
|
RE: Visual Basic Tutorial
Yeah, I forgot to give an example of recursion besides the loops form. I explained it but didn't give an example so for people interested.
Code: Module RecursionFails at coding without an IDE lol
|
|||
|
01-01-2010, 10:15 PM
Post: #4
|
|||
|
|||
|
RE: Visual Basic Tutorial
I don't know VB but I appreciate the fact of teaching others that you have made yourself through,gracias
Gholamreza Takhti who was he? find out |
|||
|
03-19-2010, 05:28 AM
Post: #5
|
|||
|
|||
|
RE: Visual Basic Tutorial
thanks man it realy help me In vb.net
Thanks 1nce again and i think now i dont have to read any eb00k this has all info |
|||
|
« Next Oldest | Next Newest »
|




![[Image: pgsig copy.png]](http://projectghostt.com/images/pgsig copy.png)


