Tuesday, February 5, 2013

.NET KeyPress Events


VB.NET Keypress Events
While messing around with the blog I found that one of the most viewed pages on here is the VBA Keypress event. If that many people are looking for it in VBA, there has to be a few who need it in .NET. I use it from time to time, primarily to handle the pasting of data from the clipboard into a datagridview, so I will share that as well.

The first piece is the most difficult, not because of complex code, but for remembering to do it. On your form go to your properties window and change the KeyPreview property to True. I never remember that part, and when I do I never remember the name. The help window for the property states “KeyPreview-Determines whether keyboard events for controls on the form are registered with the form.” In my own words “it turns on key press events”.

That was the hard part (it will be the next time you try this), the next part is a little confusing at first. Create a KeyPress event for your form. For those who don’t know how, there are 2 dropdowns just above your Public Class Form1 line of code, select (Form1 Events) from the left box, and KeyPress from the right dropdown.

You may have noticed a KeyDown event as well as the KeyPress event, there is a lot of confusion about which one to use and why. I will explain the differences in usage and translation as well as possible because each has a different purpose, and used in different ways.

Below I will provide a graphic showing which keys trigger which an event. If you want to remind yourself in the future or have other keys to test you can create an app with a couple of labels named lblKeyDown and lblKeyPress and test them yourself with the below.
The form:



 The Code:
Private Sub Form1_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown
        lblKeyDown.Text = e.KeyCode
End Sub

Private Sub Form1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Me.KeyPress
        lblKeyPress.Text = "KeyPress" & e.KeyChar
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
        lblKeyDown.Text = ""
        lblKeyPress.Text = ""
End Sub

Just  run the app and start smashing keys.
Here is the map, read below about modifiers (shift, control, alt)

KeyPress and KeyDown Event Triggers
KeyPress can probably best be summed up by saying that its’ events are triggered by character keys.
Here is a picture of the keys that trigger the events:



KeyDown on the other hand fires and event for every key I have except the Windows key. One problem that can arise is the use of modifier keys, for example when you want to copy using control C you get one event for the control key and another for the C key. However this is easily handled.
One last odd thing, KeyPress returns the actual character of the key that was pressed while KeyDown returns a KeyCode. For example if you press the “j” key, KeyPress returns “j”, but KeyDown returns 74. You have to use e.KeyCode.toString to get the actual value.

For KeyDown you may want to handle modifiers, if you don’t then A)you won’t know if one was pressed and B)depending on your usage it will send the modifier as a key when you don’t really want it. This is pretty simple though, you just use e.Control, e.Shift etc. to determine if the modifier is pressed. For example say you only want to handle a Control+C, here is how you do it:

If e.Control = True Then
            If e.KeyCode.ToString = "C" Then
                MsgBox("Control+C pressed")
            End If
End If

That should cover most scenario’s you will need. Now I’ll show you how to handle the pasting of data to a datagridview.

Paste to Datagridview
Assuming you have a datagridview named datagridview1, and you have the appropriate columns already added, the following code will paste the values in your clipboard to the datagridview.

Private Sub Form1_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown
        If e.Control = True Then
            If e.KeyCode.ToString = "V" Then
                PasteClipboard()
            End If
        End If
    End Sub
    Private Sub PasteClipboard()
        Dim s As String = Clipboard.GetText()       'Get clipboard data as a string
        Dim rows() As String = s.Split(ControlChars.NewLine) 'Split into rows
        Dim I, j As Integer                                             
        Try
            For I = 0 To rows.Length - 1
                'Add new row
                If Me.DataGridView1.Rows.Count < rows.Length Then Me.DataGridView1.Rows.Add()

                'Split row into cells
                Dim bufferCell() As String = rows(i).Split(ControlChars.Tab)
                'Copy to datagrid
                For j = 0 To bufferCell.Length - 1
                    'Remove line feed characters
                    If bufferCell(j).ToString.Contains(ControlChars.Lf) Then
                    bufferCell(j) = bufferCell(j).ToString.Replace(ControlChars.Lf, "")
                    End If
                    Me.DataGridView1.Item(j, I).Value = bufferCell(j)
                Next
            Next
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try

End Sub

Tuesday, January 29, 2013

Simple Data Binding


Links to previous articles in this series:

Interactive Controls and Simple Data Binding
In this tutorial I am going to introduce you to a couple of new controls that users can manipulate, and then tie it together with a function from the latest tutorial (last one in the links above). I will also introduce some simple data binding which will reduce the code you need when linking different controls and data sources.

Trackbar Control
You may be familiar with the trackbar control, it is essentially a slider that allows a user to change a value by sliding an arrow, the most prevalent example I can think of is the volume control on most music and video apps.
Start a new project (it’s a good idea to create new projects when possible with these tutorials giving them a descriptive name so you can easily reference them when you are working on future projects) named TrackbarDataBinding. Look in your toolbox for the trackbar control and add it to the form as well as a textbox. Drag the squares on the trackbar to make it about 3 inches wide. Name your textbox txtTrackbarValue and your trackbar trackUserInput.
First, let’s go through some of the common properties of the trackbar. Click the trackbar and go to the properties box. To make the properties easier to find, you can click the sort alphabetically icon on the properties box.


Find the Maximum property and set it to 100, this makes the maximum value of the trackbar 100. Leave the Minimum at 0. So we can see what some of the other settings do let’s add a piece of code that will put the current value into our textbox. Double-click the trackbar, this should open the code page and create a scroll event. Place the following line in the event and click run.
Me.txtTrackbarValue.Text = Me.trackUserInput.Value
Click the trackbar arrow and drag it around, notice that the textbox value changes as expected. Now set the trackbar back to zero, then click another point somewhere along the control, the value should increment by 5 each time you click. Page Up and Page Down perform the same task, this jump of 5 is controlled by the Large Change property. If you press the left or right arrow or the up and down arrow the number will increment by 1, this is the Small Change property. Another useful property is Orientation, this will let you display the trackbar horizontally or vertically. Go ahead and play around with the settings and get comfortable with how they work.

Databinding
Databinding is a way to bind controls and data together, similar to what we did above by setting the textbox’s text property to the value of the trackbar. The benefit comes in when you need to do something a little more complex. From the example above, imagine that we want to let the user choose whether to use the trackbar, or just type the value they want in the textbox. To do this in code, you would basically do what we have already done, then you would need some sort of event that would know when the textbox had been updated so it could then set the value of the trackbar. Databinding simplifies this greatly. Delete or comment the line of code you already have, then create a form load event by going back to your form and double-clicking the top bar of the form. Now we can create the binding when the form loads and the two controls will be tied together whenever the application runs and stay that way unless you change it.
In the form load event add the following line.
Me.txtTrackbarValue.DataBindings.Add("Text", Me.trackUserInput, "Value")
The first part just tells that we are going to add some sort of databinding to our textbox. The “Text” piece says that we will be binding the text property of the textbox. The middle section tells what control we are binding to, and “Value” says that we are binding to the value property of the trackbar. That’s it, run the application and try out the trackbar, then then try typing a number (0 to 100) and press tab to leave the textbox, the trackbar should now show the value you typed in the textbox.
While this may not seem like it saves a lot of code, once you are binding multiple controls or tying into a database the usefulness will become apparent quite quickly.

Integrating a Function
Now let’s tie our trackbar to a function. Start by adding a label to the form from the toolbox and name it lblMultiply, a label is similar to a textbox but is for displaying data only; it does not accept user input.
As you did in the last tutorial add a function and the required parameters:

Function multiplication(intVal, intMult)
        multiplication = intVal * intMult
 End Function

 Back in your trackbar scroll event (double-click the trackbar on the form if you deleted the event) type:

Me.lblMultiply.Text = multiplication(Me.trackUserInput.Value, 10)

This will set the text of the label to the result of 10 times the trackbar’s value. Run the application and test out the trackbar, the label should update with the formula result, but notice that if you change the textbox manually the trackbar updates but the label does not. The reason for this is that the event we created was for the scroll event of the trackbar. Remember that the binding is tied to the trackbar’s value, this sets the position of the trackbar but it does not cause it to scroll, that can only be done by the user. How do we fix this then? Well, we know that the value of the trackbar changes, so we need to create an event that fires when the value changes. To do this, you need to be introduced to another helpful feature of .NET. Near the top of the screen you will see two dropdowns, the content of which depends on where your cursor is at the time.



These dropdowns help you create events, showing all possibilities for the selected object. Drop the left one down to choose the object, in our case trackUserInput. The default is the scroll event and if it has not already been created, it will be. Now drop down the right box and select ValueChanged, this should create a new ValueChanged event. Move your code to set the labels text to this event, it should now look like this.

Private Sub trackUserInput_ValueChanged(sender As Object, e As EventArgs) Handles trackUserInput.ValueChanged
        Me.lblMultiply.Text = multiplication(Me.trackUserInput.Value, 10)
End Sub

Now run your application and test the trackbar as well as the textbox, you should see that the label updates with either one. The lesson here is that you have to think through what your events are doing, if something isn’t working look through your events and see if you can find something else that might work.
Here is the code that gets everything to work in case you ran into trouble

Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Me.txtTrackbarValue.DataBindings.Add("Text", Me.trackUserInput, "Value")
    End Sub
    Function multiplication(intVal, intMult)
        multiplication = intVal * intMult
    End Function
    Private Sub trackUserInput_ValueChanged(sender As Object, e As EventArgs) Handles trackUserInput.ValueChanged
        Me.lblMultiply.Text = multiplication(Me.txtTrackbarValue, 10)
    End Sub

End Class


DataTypes. Subs & Functions


Links to previous articles in this series:

Data Types
*Note that these calculations can vary a bit so they are not always 100% correct but good enough to cover almost every instance.
Before we go too far into programming we will need to understand a bit about data types. I like to think of data types like boxes we want to put stuff in, when packing a house we need the right size box to hold all of our stuff; a microwave box is too small to fit a couch but is too big for a pair of shoes. The same is true for data. One of the main reasons we choose data types carefully is to maintain a balance between scalability and size. For example if we are storing a Boolean value (1 or 0, true or false) we want to choose a data type that will accomplish the goal without going overboard.  To store our Boolean value we can choose the Boolean data type, (this will always be right as long as we are only using it for Boolean) this type is about 1 byte, so storing 1 million values would take about a megabyte (MB) of memory . Storing the data as a long (more on this type soon) is possible, but overkill, our box is too big for our needs, so storing the same 1 million values would take 7.6 MB. The more memory we have allocated for unnecessary data the less we have for other things and we also take a performance hit.

On the other side of this coin is scalability, I have seen on numerous occasions where someone chose something like 4 bytes of data for their data type assuming that it would never be larger than this, only to find in the future they need more data and need to rewrite several pieces of code. Take for instance zip codes; prior to 1980 all zip codes were 5 digits and most people thought that would always be the case, but now many systems use a Zip+4 which brings the total to 9 digits, or 10 if you include the hyphen. All applications that restricted zip codes to 5 digits had to be re-written.
When programming for small platforms such as cell phones or robotics memory is a premium so special consideration must be given to data types. Larger systems aren’t generally as constricted so it is often better to err on the large side.

This link goes into much more detail about all of the data types used in visual studio if you want to use it as a reference. I will detail the ones I most commonly use after the link, you can use the link to look up the specifics at the link.

·         Boolean:              1 Byte                   Store True/False data
·         Byte:                    1 Byte                  Commonly used for colors
·         Double:                8 Bytes                 Covers most decimal numbers
·         Integer:                4 Bytes                 *Covers smaller whole numbers
·         Long:                   8 Bytes                 *For larger whole numbers
·         String                   Depends               Used for storing text up to 2 billion characters

*In Excel 2003 Integer was as large as you needed for most programs dealing with cell references as the maximum row number was 65,535 and 256 columns for a total of 16,776,960. This easily fit in Integer’s 2.1 billion value range, but Excel 2007+ expanded the rows to  1,048,576 and columns to 16,384 which gave about 17 billion possibilities, greatly exceeding the Integer data type but easily within the Long’s 9 quintillion limit (a quintillion is 1 billion billion), not bad for only 4 extra bytes!

Long story short, use Boolean for Boolean, Double for decimals, String for text, Integer for relatively small numbers, and Long for large numbers. Unless I plan to use a lot of memory, I default to Long for whole numbers.

Using Data Types
Keywords are words that have special meaning to Visual Studio, and they cannot be used as variable names, if you try you will get a “Keyword is not valid as an identifier” error, so don’t worry about doing it by accident. One of the most common keywords you will use is “Dim”, the DIM keyword lets the program know that what comes next is a variable definition.

Using the training file you created earlier, or a new one with a button added named btnDisplayMessage, add the following line of code just beneath the button click even Sub.

Dim boolTest as Boolean

As with controls, it is good practice to preface the name of your variable with the data type, this helps later on in your code with filtering names and ensuring the data type will fit the data you want to add to it.
Then add 2 more lines, the first will assign boolTest a value, the second will display this in a messagebox.

boolTest=0
MsgBox(boolTest)

Notice that boolTest is not in quotes, this is very important; if you want to display the value that your variable currently contains you just use the variable name, if you put it in quotes you would just see “boolTest” in your  messagebox.

Click run, a messagebox should pop up displaying “False”, this is because with Boolean types 0 = False and 1 = True.

Now change your line to say boolTest = 10<20 .="" and="" application="" booltest="" calculates="" depending="" equation="" false="" o:p="" on="" or="" result.="" returns="" the="" to="" true="">
Now let’s add in a new data type and perform a calculation.
Delete the code your wrote, and now create 3 integers, 1 named intValue, 1 named intMultiplier, and 1 named intResult.  Set intValue=5, intMultiplier=10, and then set intResult to the product of the multiplication. Finally, display the result in the textbox (txtOutput if you do not have it).



If you did everything correctly, 50 should appear in the textbox. That covers the basics of creating and assigning variables, performing calculations, and displaying results.

One last note here is related to scope. This code works for the button click, but if you were to try to perform the calculation in the load event of the form you would get errors and your application would not run unless you put the DIM’s in the load event. This is because the DIM’s only work within the event they are created in. If you want to create variables that are accessible from anywhere in your application, you just move them out of your Sub’s and place them just below the first line.



Why not just make the variables accessible to the entire program always? Once you DIM the variables memory is assigned to them and stays with them until the application closes or the Sub using them closes. Say you were creating arrays of variables (more on them later) and you filled your array with 1 million pieces of data. If you create the DIMs at the application level, at the top, the memory will be held until the application closes, but if you put it in the event like our first example the memory is released as soon as the click event completes. Dimming everything at the beginning of a big application can quickly use up all available memory, so it is best to do it only when necessary.

Subroutine and Function
There are 2 primary methods for executing code, the subroutine (Sub) and the function. As mentioned in a previous article a sub performs an action, a function does the same, but is used to return a value. Generally you will see a Public or Private keyword before your subs and functions, I will go into further detail later, but the general idea is that Private means the code can’t be called from outside of the current class.

Taking our code from above, let’s create a sub and a function, starting with the sub.
Start by typing “Sub multiplication” and press enter (note that this must be below the Public Class Form1 and outside of other subs) VS should complete the line as well as add an End Sub below. Next, copy the multiplication data from the button click event above and paste it into this new sub and delete the code in the click event. Your code should look like this:





Now to execute the calculation we have to “call” the sub, we do this by typing the name of the sub (multiplication) before the button click event’s end sub. As you type, intellisense ought to pop up with the name, you can hit tab to accept it, the press enter. This will add parentheses to the end, this is how you can tell it is calling a sub. One handy shortcut that will become more valuable as your code grows larger is hitting Shift+F2 after clicking within the sub name you just typed, this will place your cursor at the beginning of the sub. This is handy when working with a sub later and you need to see what is inside or make a change but don’t want to search all of your code to find it. Hit run and click your form button, you will get the same result as you did when the code was within the click event. The main reason for putting this in a sub vs. in the event itself is when you want to use the same piece of code from several different events.

Now let’s create a function, you can create one from scratch, or just change the word sub to function on the method we just created, notice that the End Sub is automatically changed to End Function. If you run this now you will get the same result as before, but let’s go  a step further to illustrate the power of the function.

You’ll remember that when something is dimmed in a sub (or function) the data is released when the sub ends, functions allow you to return data to other subs or functions. Move your code back up to the button click event above where you called multiplication(), it must be above because code executes from top to bottom. Now delete the line: intResult=intValue*intMultiplier. Within the parentheses on your function type “intVal, intMult”. Your code should look like this:



There are 2 things to notice, first is the green line under the End Function, hovering over it you see that the function doesn’t “return a value on all code paths” which is a problem since the purpose of a function is to return a value. We will fix this soon. Now hover over our second issue, the blue line beneath multiplication(). You will see an error related to an argument not being specified, this is because by placing intVal and intMult in our function that the function now requires 2 parameters. Change the multiplication() line in the click event to multiplication(intValue, intMultiplier) this is called “passing parameters” to your function. Now your function is receiving our variables, which in this case is a 5 and a 10. Next we want to perform the calculation, to do this add the following line to the function: multiplication=intVal*intMult
This performs the calculation and sets the result to the multiplication function. The function will perform right now, but we need to set the result to intResult before we display it, so in the click event type “intResult=” before calling our function, and move the txtOutput line below like this:




Now run your application and click the button, you should get the same result as before. What makes functions so useful is that you can create the function once, then call it from anywhere in your program passing in any variable you want. Just as an example, change your parameters to 10 and 50 and run it again, you will see that the function performs its task on anything you pass in as long as it can be performed.




While you will generally want to create variables, you can simplify all of this by calling the method and displaying it at once:



We will go into more advanced functions in future articles, but this should be enough to get you going for now.





Monday, January 28, 2013

Hello World!

Hello World!
Historically most programming languages start off by creating a simple application that displays a “Hello World!” message when run. We will get there, but I want to show some other things along the way.
The first thing I typically do when creating an application is to drag the bottom right corner of the form out to make the area I am working with larger. The size you make it in the designer will be the size it appears when you execute your program, so keep that in mind.

The Form
There are many properties to a form, but only a few of them will make any sense at this point.
At the top left of your form you will two items that are changed frequently, the icon and the form name, which is likely Form1. When your application is run, this will be the icon and name that your user will see. Select your form by clicking on it, and go to your properties window.
·         Icon: Your application will default to this standard icon, by clicking the ellipsis button […] you can choose your own icon. Most images will work, but you may have to convert/resize them.
·         Text: This is the text that will be displayed on your form when the application is run; you will typically want to change this to something more meaningful to the end user.
·         WindowState: This sets the beginning window size when the user launches your program. The default is Normal, which is the size you dragged it to in your IDE but you can also change it to maximized (most common) or minimized.
For our example change the icon if you desire, change the text to “Hello World!”, and leave the windowstate as normal.
Your form should look something like the image below. Just under the menu you will see a green arrow, or “play” button and the word “Start”, click the button to execute your application.


Click the red ‘X’ on the form or the red stop square that is now available where you clicked the start button before.

Working With Controls
Controls are pieces of prebuilt code and design that can be used over and over again. Before modern IDEs and interfaces if you wanted a button for example you would basically have to draw a square to the screen at the specified location, color it and add text, add properties and events to handle what happens when someone clicks it, program a sound if you want it to have an audible click etc. etc. A control allows you to create usability that covers most situations, and package it all together to be changed and edited as needed.
Open your toolbox and find the button control, you may have to first click on “All Windows Forms” or “Common Controls”, the controls should be displayed in alphabetical order. Click on the button and drag it onto the form. Your form should now look something like this.


 

Note that when the button is selected, you will see little white boxes called handles that allow you to resize the button. With the button selected open your properties window.

At the top of the properties box just under the blue line you will see the name of the button in a drop down list, in our case “Button1”. You can also use this dropdown to select controls, this comes in handy when you have controls that overlap or hidden. The first thing you generally want to do when adding a new control is change the name, because once you start writing code you might not remember what Button1 is. While there are not any universal naming conventions, it is usually helpful to develop your own and be consistent, the reason will become apparent soon. For buttons I preface my name with btn all lower case, and you will not be allowed to use any spaces, so generally you replace a space with a capital letter. Scroll to the top of your properties box and change the “(name)” to btnDisplayMessage.



Notice that the dropdown box at the top automatically changes to the new button name.
This next step is not anything you will want to do on a regular basis, but I want to show it to you so you can understand just how much the IDE is helping you. Go to your Solution Explorer, and at the top right you will see the icon I have highlighted below, hovering over it should display a box for you telling you what the button does, in this case “Show All Files” click it. Now you will see some additional files that the IDE hides because you will rarely use them and they can mess things up severely if you don’t know what you are doing. Click the little arrow beside the icon “Form1.vb” and then double-click the icon “Form1.Designer.vb”.


This will open another tab at the top of your screen. This is the code that the IDE created when you put the button control on your form. You can see how much work the IDE is doing for you; I have 50 lines of code that was created for me without having to write a single line myself. Before we accidentally mess something up, close the designer tab with the little “x”, and click the “show all files” icon again to hide the files we don’t need.
I forgot to change the name of the button, so click on it and go to properties and change the Text property to “Hello World”. Note that for the text property  you are allowed to type any characters.
Explore some of the other properties if you would like, such as Font, which allows you to change the font of the text displayed on the button.

Your First Code
For this first piece of code we will write the code first, and then I will explain what everything does. To write code for the button, double-click it. This should do a couple of things for you, first it opens up a new tab called “Form1.vb”, and it puts some code in for you.
Private Sub btnDisplayMessage_Click(sender As Object, e As EventArgs) Handles btnDisplayMessage.Click

End Sub
Note that my writing may move some text to the next line, your code should have the entire first part on one line, a blank line, and then a third line “End Sub”
In the space between Private Sub… and End Sub type the following:
MsgBox("Hello World")
Your code should now look like this:





This page also has a Start button under the menu, click it. Your form should now open and you should see your button on the screen, click it.
There’s your first line of code!
Click OK on the message box and stop your application.
Now to explain a little bit about the code and what it does. First, each form that you create will have its own code page, which will by default include “Public Class Form1” or whatever the forms name is, as well as an “End Class”. For the most part, any code that is written for your form will be done between these two lines, we will go into more details about what a class is in later sections.
I won’t go into detail right now about the sender, EventArgs etc. The important parts here are the Sub and Handles.
Sub stands for Subroutine, its counterpart is the Function; for the most part these are the same, but Subs are designed to execute a piece of code while a function is designed to do something such as a calculation and return a result. Don’t worry too much about the Private piece right now.
If you were to just type MsgBox(“Hello World”) in the code page without a handles, nothing will happen except a few errors, you have to tell the code when to display the messagebox. The handles accomplishes this. From the example above you can see that the handles was put in for you “btnDisplayMessage.Click”. This tells the code to execute only when the button we created is clicked, this is called an event.
Go back to your Form1.vb tab, and then double click the top of your form, by “Hello World” for example.
This will take you back to the code page where you will see that some new code was added.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

End Sub
A new Sub was created for Form1_Load, notice that the handles may not be what you expect such as Form1.Click. What it did do was create a sub that is executed when the form is first loaded, any code you put here doesn’t require anything from the user other than starting the application. In the sub type in the code
MsgBox("Form Loaded")
And click the run button. This time you’ll see that you get the messagebox before the form is displayed. When you want code to run when your application starts, you put it here.
As you started typing the code for the messagebox, you should have seen something pop up on your screen that looks like this.


This is called Intellisense, it guesses at what you are typing as you type, which can save you time or help you to remember the name of what it is you are trying to do. Further, there is a box that comes up that tells you what the code is expecting next, like when you write a formula in Excel and it tells you what it wants next. I will walk through each of these briefly.
  • ·         Prompt As Object: This is the message that you want to display within the messagebox, this message must be in quotes. At the bottom of the popup you will see “Prompt:…” This gives you more information about what is expected next, it tells you it is required and what it does as well as the limitations such as 1,024 characters.
  • ·         Note that for the rest of these the description is in brackets “[]” this means they are optional.
  • ·         Button As Microsoft.VisualBasic.MsgBoxStyle: A dropdown will appear to help you select this, which is an icon that will appear on the messagebox, choose Critical.
  • ·         Title As Object: The title for the messagebox, type “This Is The Title”

Click run to launch the application. You should now see a messagebox like this:


Textbox Control
Before we finish this tutorial I want to introduce you to another of the most common controls, the textbox. A textbox is a place where you can display text or receive text from the user. Go back to the IDE and look for textbox in the toolbox and add it to the form.


Note that when the textbox is selected you see 2 squares, one on either side which is for resizing the width. The standard textbox is for single lines of data, but it you click the little right facing arrow at the top right corner of the box you should see a checkbox for MultiLine:




 Once you check this box you see that there are now 8 little squares so you can resize the box in any dimension. Unless you are displaying multiple lines of text to the user, you would generally leave this as single line. The right facing arrow is on several controls and gives you quick access to some of the most common formatting selections; you can also achieve this from the properties box by setting the Multiline property to true. Change the name of the textbox to txtOutput.
Now instead of displaying our message in a messagebox, we are going to put it in the textbox. While working on code you will often want to insert a messagebox to see what a particular variable is at any given time, instead of writing and deleting them several times you can comment them out, this leaves the code there but does not execute it. Go back to your code and put a tick mark “ ‘ “ before the 2 lines containing the messagebox. If you need to comment many lines at a time you can use the comment/uncomment icon from the menu.

Now we want our button to populate the textbox with our message, go to the click event for the button (where the handles has the .Click method, or double-click the button again). Now type “Me.txtOutput.Text=”Hello World!””. The “Me” in the code makes the code refer to the current form, this isn’t necessary but is often helpful as it will reduce your list of options making the intellisense show results closer to what you need. Your code should now look like this.



Click the run button, your textbox should still be blank, but when you click the run button your textbox should populate.
One last note for the textbox, you can have it default to a certain text by setting the text property to whatever you would like in properties of the textbox, if you do it this way you do not need to put the text in quotes.

Code from project:
Public Class Form1

    Private Sub btnDisplayMessage_Click(sender As Object, e As EventArgs) Handles btnDisplayMessage.Click
        'MsgBox("Hello World")
        Me.txtOutput.Text = "Hello World"

    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        'MsgBox("Hello World!", MsgBoxStyle.Critical, "This is the title")

    End Sub
End Class