CyberiaPC.com Main Page




Learning VB

Manipulating Strings and Integers

There are many small things that can be done to data types (integers, strings...) in VB that make the life of the programmer much easier.  In this section, I'll discuss the most important and the most widely used techniques for manipulating numbers and characters.  Here is an index of what will be discussed in this lesson:

 
Converting Data Types
Constants
Dates and Times
Using the Format Function
Manipulating Text Strings

Converting Data Types

Visual Basic can automatically convert certain data types for you.  For example, if you place a string variable of "20" in an integer variable, VB will automatically make the conversion and recognize the string as a number.  Additionally, calculations can also be made between strings and integers, for example: "10" + 5.  However, this automatic way of converting between data types may not always be in the programmer's benefit.  For example, "10" + "10" would give "1010" instead of 20.  Therefore, it is best for the programmer (you) to use certain bug-proof commands for converting data types.

Conversions can be very important, especially when different controls in your project interact with each other.  For example, if you want to multiply two numbers in two text boxes and then store the result as a double (a number with fractions), you'll need to convert the result to double before transferring it into your result variable.  Another example would be placing a double value in the Caption of a label.  To do this, you'd have to convert the double to a string first!  Don't worry, I'll show you some examples later on.

Here is a table of the conversion functions in VB:

To Convert to... Conversion Function
Boolean CBool
Byte CByte
Currency CCur
Date CDate
Decimals CDec
Double CDbl
Integer CInt
Long CLng
Single CSng
String CStr
Varient CVar
Error CVErr

The general syntax for conversion calculations is:

     variable1=CFunction(variable2 or formula)

Here is an example that converts contents of a string text field to a double number (Without the conversion, VB would automatically convert the result to an integer):

     dblResult = CDbl(txtNumber1.Text * txtNumber2.Text)

Here's another example that displays the result of the above calculation in a label's caption:

     lblShowAnswer.Caption = CStr(dblResult)

The CStr function converts the answer back to a string so that it is displayed properly in the label's caption property.  To be able to specify the decimal places of the double number even after conversion, we'd have to use the Format Function.  This is discussed later on in this lesson.

{Go Back To VB Lessons Page}