User Defined Type (UDT)
In this tutorial, you will learn about User Defined Type (UDT).
Visual Basic has many data type such as Integer, String, Double, Single, etc. Aside from those intrinsic data type that has been provided by VB, you can create your own data type by combining several different types. This UDT is useful to create single variable contain several useful information. It is usually useful for database record. You define the UDT using syntax:
Variable1 as varType1
Variable2 as varType2
VariableN as varTypeN
After that you can declare any name as this new variable type and use it as ordinary variable.
Note: Special for this project, please do not copy and paste from this tutorial. Type the code manually so that you may understand the different between UDT and normal variable.
- Create new Standard Exe project
Private Type City
Name As StringEnd Type
Population As Long
Diameter As Double ' in km
Year As Integer
- Add one Frame control; change the Caption property to City.
- Add 6 label, 4 textboxes and one command button into the Frame1 . Change the Caption of the labels respectively into: Name , Population , Year , Diameter , million , km . Change the Name property of the textboxes respectively into txtCityName , txtPopulationNumber , txtYearOfRecording , txtCityDiameter . Change the Caption of command button to Enter , and the Name property to cmdEnter .
- Arrange the controls so that it looks nice.
Double click the command button and type the following code:
Private Sub cmdEnter_Click()
Dim myRecord As CityEnd Sub
myRecord.Name = txtCityName.Text
myRecord.Population = txtPopulationNumber.Text
myRecord.Year = txtYearOfRecording.Text
myRecord.Diameter = txtCityDiameter.Text
MsgBox myRecord.Name & " city has population of " & _ myRecord.Population & " million people " & vbCr & _
" and diameter of " & myRecord.Diameter & " km in year " & _ myRecord.Year
- Run the program and try the data for some real city.
You see that UDT combine several data type into single unit. in the next lesson, you will learn how to combine several data type plus several sub procedures and functions into a single unit.