Home and Learn: VB Net Course

The Trim Method in VB .NET

This lesson is part of an ongoing tutorial. The first part is here: String manipulation

In the previous part you added code to transfer some text that was in a Textbox over to a variable. The code you wrote was this:

Dim FirstName As String

FirstName = txtFirst.Text

If FirstName = "" Then

MessageBox.Show("Please enter your First Name in the text box")
Exit Sub

End If

But the user could press the spacebar in your textbox. Although there would be no letters or numbers inthe textbox, the above error checking wouldn't work - all of the blank spaces would get passed to your variable. We can use a String method called Trim to solve this problem.


The VB NET Trim Method

One of the methods on our list was Trim. What this does is to trim any leading or trailing blank spaces from a string. So if the string was " Text", then Trim would delete those spaces for you, leaving just "Text".

You use it in your code. Like this:

FirstName = txtFirst.Text
FirstName = FirstName.Trim

First, we put the text from the textbox into a variable called FirstName. Then we said "assign to the variable FirstName (FirstName = ) the value of FirstName trimmed (FirstName.Trim)".

Again, though, we're just adding the method we want after the variable name. VB will take care of the trimming for us.

Another way to Trim is to use the Trim() function directly. Like this:

FirstName = Trim( txtFirst.Text )

What you are trimming here is any blank spaces from around text entered directly in the text box called txtFirst

But we now have a way to thwart that user who is trying to trip us up by entering blank spaces into our text box. If you were programming a Form where the First Name was going into a database, then it's essential you trap anything like this.

OK, we've tested to see if the First Name text box was empty. Is there anything else we can do? What if our clever-clogs user tries to fool us again. This time he (they're always "he's"!) decides to enter some numbers. He claims his name is "George12345". Is there anything we can do to stop his little games? Is there a way to test that the data entered into a text box was text and not numbers?

Indeed there is! We'll use the Chars Property to see if we can check for numbers and text. You'll also see the difference between Chars and Char.

Back to the VB NET Contents Page


Buy the Book of this Course

Email us: enquiry at homeandlearn.co.uk