ProgrammingVB.NET Beginner's Guide
Posted:
ProgrammingVB.NET Beginner's GuidePosted:
Status: Offline
Joined: Oct 01, 201113Year Member
Posts: 2,845
Reputation Power: 19778
Motto: Brandon has stopped paying for his motto advertising space. This motto is now vacant.
Motto: Brandon has stopped paying for his motto advertising space. This motto is now vacant.
Status: Offline
Joined: Oct 01, 201113Year Member
Posts: 2,845
Reputation Power: 19778
Motto: Brandon has stopped paying for his motto advertising space. This motto is now vacant.
Hi everyone, I haven't seen any posts like this in a while, I know speed used to have a bunch of programming tutorials stickied but it looks like they're all lost to time. So have a good read, take some time, and hopefully learn a thing or two about one of my favorite languages .
Why VB.NET? VB.NET is a Microsoft .NET Framework object-oriented language and the sibling of C#. VB.NET applications can be assembled and ran on any machine running Windows, and are excellent for creating database and even some commercial applications. It's an excellent starting language because of it's resemblance to english, and understanding it opens the door for an easier time learning C# than just learning it out right. I've designed hundreds of useful VB.NET applications, and the speed at which applications can be created from start to finish makes the language very appealing for quick projects. Getting Started The first thing you should do is download Visual Studio (VS), which is far and away the best VB/C# IDE. The community edition is 100% free.
Download: visualstudio.microsoft.com/vs/ This is the 2019 version, but any screenshots in this post will be coming from VS 2017. There shouldn't be many differences, but if you need any clarification between versions please reach out. Once you have it installed, open it up and you should be met with a start page. Click File > New > Project and you should be met with a pop-up form presenting you different project options. For this tutorial, we will be creating a simple desktop application, so make sure the "Installed" node is selected, and then click Visual Basic > Windows Classic Desktop > Windows Forms App (.NET Framework). https://i.imgur.com/80QFYug.png You should now be met with a blank form and are ready to begin. Navigating the IDE Now that you have a new application started, let's take note of what you should be seeing.
https://i.imgur.com/n7hEHxs.png We will mainly be focusing on the Properties window you can see off to the right of my version of VS. If you can't see it by default, click View > Properties Window or simply hit F4. You can peruse these properties and some of them should be relatively self-explanatory. BackColor changes the background color of the form, Text changes the header text, Location and Size determine the screen location and form size. Plenty of them will need some experimenting to figure out how they work, for instance FormBorderStyle determines both how the form border appears, and how the user can interact with it. Most of the properties are safe to mess around with and see how they work. The most important property for our purposes is Name, this is NOT synonymous with Text. The Name property determines the word that VS will use to refer to that specific object. Changing the name of an object changes how you will need to refer to it in code. First Peak at Code Let's take a look at some code and dissect what we're seeing. Go ahead and double-click anywhere on the form object. You can also right click and click View Code.
You will see four lines of code. The first is a class definition with the name of your form. Classes help to encompass and organize your code into objects which allows the communication between functions and other objects inside the class. Classes are extremely useful for organizing code, but for now we won't delve too far into it, it's only function as of now is to keep all of our code contained. The next line of code should look something like this: Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load Now this line of code is a bit more loaded, and each word is important, but for now we will only focus on a few things. The word Sub declares a sub-procedure, inside subs is where code can be executed to accomplish tasks. Form1_Load is the name of this particular Sub, and it can be referred to in other Subs within the Form1 Class by calling Form1_Load. "Handles MyBase.Load" tells us that this particular sub handles an event triggered by a control object. MyBase refers to our application, and Load refers to our application loading. So any code written inside this Sub will be triggered when our application is started. End Sub and End Class close their respective subs/classes, and any code put between these tags belong to the sub/class that they close. Make Something Happen Now that we have the basic outline figured out, let's take a look at how these work. Between the Sub tags, write the following code:
MsgBox("Hello, world!") https://i.imgur.com/wVUc8fZ.png Now press the green Start button or press the F5 key and that will start debugging your application. You should have a plain message box pop-up saying Hello, world! https://i.imgur.com/i1RPeaz.png Once you hit OK, your blank form should then pop-up. You can close it to end the debugging session and get back to the code. Working With Controls Let's go back to the designer by clicking the Form1.vb [Design] tab. Let's drag the edges of the form to make it a bit bigger. You should see a pinned tab on the right side of the screen called Toolbox, click that and expand the common controls node. If you don't see the toolbox, click View -> Toolbox.
https://i.imgur.com/vCFSkHq.png Go ahead and drag and drop 2 textboxes and 1 button onto the form. https://i.imgur.com/Fz97Hu1.png I'm going to change the text property of the TextBox to say "Add" Now double click the button to view its code. https://i.imgur.com/btjB4HV.png Let's delete the code inside the load event sub, since we don't want it to bother the user by opening every time. Now, under the button sub, add the following code. Dim a As Integer = TextBox1.Text
This is a bit more loaded than the code before, but should be straightforward. The Dim keyword means dimension which declares a variable in memory and assigns it a data type definition. The word/character that follows the word Dim is called a variable, and variables refer to a value. So in this case, both the letters a and b are now variables. In VB.NET, we declare the data type for a variable by typing As [Data Type] which in this case is Integer. There are dozens of data types including strings, dates, times, doubles, and just about anything else you can need. Different data types handle different types of values and are treated differently. For instance, integers handle whole numbers, like 5, 10, 20, 100 etc. while floats handle decimals like 5.1, 10.1 etc.. Strings handle text, for instance, this entire post could be stored as a string. We are assigning a and b to the value of the textboxes. TextBox1 and TextBox2 refer to your two textboxes on your form. The Textboxes have dozens of properties and functions. You can see how many by typing TextBox1. and seeing how many autofills intellisense has available. The Text property refers to whatever text is inside the TextBox. Users who add text to the textbox change its text property, which can then be manipulated in code. So, this code assigns the variable a to the text contained in textbox1, and b to the text contained in textbox2. When a user clicks Button1, the application adds A and B together, and shows a messagebox with the result. Let's try it. https://i.imgur.com/lXlv5gw.png Conditionals That was a cool little calculator, but let's see if we can have it tell us something about the data. Conditionals have the application check some sort of information, and then return a certain result depending on the outcome. In VB.NET, they are formatted like this:
If x = y then z So let's say we want to only know if the outcome is greater than 10, we don't care about the actual number, just whether it meets some sort of threshold value. Let's change the code in the Button1 Sub to this: Dim a As Integer = TextBox1.Text
We have now set the value of a + b to a variable named result, then using a condition, we are checking to see if result is greater than 10. There are lots of ways to compare including >, <, >=, <=, = (greater-than, less-than, greater-than or equal to, less-than or equal to, equal to) and all compare two integers (except = which can compare strings as well). Go ahead and run the application: https://i.imgur.com/F00KlMp.png If you enter two values that add up to more than 10, you will get a messagebox saying so. But what if you don't? Nothing happens! Let's fix that. Update the code to:
The Else statement handles the result if it doesn't meet the requirements of the If statement. Now if you put in numbers less than or equal to 10, you will also get notified. Functions So now we have a small calculator application that tells you whether a value reaches a certain limit. Right now, it's very small scale, but what if we wanted to scale up the application later? The best thing to do when dealing with simple repetitive tasks, is to add them to a function that can be called. Click below the End Sub that ends the Button1_Click sub and type:
Function add(a As Integer, b As Integer)
This creates a new function called add, that can be called to add two numbers together. You will see there are two declarations separated by a comma between the parentheses next to add. These are called parameters, and they are values that must be passed to the function in order for it to work. In this case, they are two integers that we want to add, but they could be any data type. You will see we have made a new variable called outcome to hold the added value of a and b. We then use the Return keyword to send this value back to whatever method calls the function. We will now also edit the Button1 code to: Dim result As Integer = add(TextBox1.Text, TextBox2.Text)
Here we are calling the function add, and assigned the returned value to the variable result. You will see that we are passing the text from the two textboxes as the parameters, in this case two parameters MUST be passed, and trying to pass any more or any less will immediately stop debugging. The way of passing these parameters is better than declaring two new variables to hold the text from the textboxes, since that fills memory space and if we don't have to set variables, it is sometimes best not to. Go ahead and run the code, and when you press the button you should get the added result. https://i.imgur.com/oM0wwcX.png We get the same result as before, and we've offloaded a lot of the Sub's code into a reusable function. Iteration Sometimes we need to do a task multiple times, and while it might be possible to just type a function a bunch of times to keep calling it with new values, iterators make it much easier. There are a iterators, but we will focus on the For loop.
The For loop is structured like this: For X as Integer = Y to Z Let's have the application count to whatever number we calculate. Change the button1 code to this: Dim result As Integer = add(TextBox1.Text, TextBox2.Text)
In this for loop, we are declaring the variable i as an integer that is equal to 0, and then we went to loop through the code we have provided until we reach the result. If you run the code, you will find that the application gives you multiple messageboxes and count up until it reaches your result. Strings Strings are a datatype that store text, and can contain almost any character. They are extremely malleable and you manipulate them in many ways. Let's add a button to our form and change the text to concat.
https://i.imgur.com/Grd8KXA.png Let's double click it and add some code. Dim concat As String = TextBox1.Text & TextBox2.Text
Go ahead and run the code, and add text to each textbox. When you press the concat button, you should get a messagebox that combines the two strings into one. https://i.imgur.com/TvlJY7c.png Let's take another look at using a for loop and the Length property of strings. We will have the application go through and tell us each character inside the string. Let's change the button2 code to this: Dim con As String = TextBox1.Text & TextBox2.Text
You'll notice here the same For loop logic as used in the number example, but here we are setting the limit to the concat string's length minus 1. It is important to remember that VB.NET is 0-based, meaning that the first item in any list or array is item 0, and not item 1. And so, if we have string "test", the first character would be item 0, and the last item would be item 3. Meanwhile, the length of that string would be 4, and so if we attempted to refer to item 4, it wouldn't exist and we would get a logical error. Using numbers like this, we can refer to individual characters in strings via string(i). If we have variable Var which is a string equal to the word "Fold" then Var(0) = F, Var(1) = o, Var(2) = l, Var(3) = d. Let's run the code and watch how the loop breaks up the word into characters. I think that's where I'm going to end it for now, I'm quite tired. My plan is to either add to this one or make a part two, with other beginner topics like lists, arrays, classes, webclients, tries, and then eventually do intermediate topics like memory management, Regex, datagrids, SQL queries etc. |
Users browsing this topic: None