Visual Basic allows programmers to define a Visual Basic User Defined Data Type. A well-constructed User Defined Data
Type can help make a program easier to understand and work with. One example of a Visual Basic User Define Data Type is the Structure construct. The Structure
Data Type is composed of two or more standard data types. Some examples of Visual Basic standard data types are: Integer, Double, and String. So, some
company like Jenny Craig can combine a string for the member's name and a double for their current weight. An example of how this might look coule be something
like: Member.Name="Kirsty Allie" and Member.Weight=288.6. The structure construct gives a convenient way to group attributes (like name, weight and age) with
a common object (like Member or pigeon or even MealTicket).
Visual Basic Structure Declaration Syntax
Syntax: Private/Public Structure StructureName
Private/Public:
Private: Example: Private Structure Employee. Private is used to limit scope to module.
Public: Example: Public Structure Student. Public is used to give scope to entire project.
Structure: Keyword Declaring Structure Construct.
StructureName: User supplied name to describe name of Structure Construct.
A structure may not be defined locally within a procedure or function - It must be public or private.
The Visual Basic IsNumeric Data Validation Function is an intrinsic function in VB.NET that takes string
data as an input argument, and checks it for being a numeric string. The functiion returns a Boolean output of true or
false. Often, the IsNumeric function is used to check the data entered into a TextBox for being a numeric string. Typically,
the IsNumeric function is used in conjunction with an If...then statement.
IsNumeric Function - General Syntax:
IsNumeric ( string expression )
IsNumeric Function Used for Data Validation:
Private Sub btnCalculate_Click(ByVal sender as System.Object, _
ByVal e As System.EventArgs) Handles btnCalculate.Click
If IsNumeric ( txtSubtotal.Text ) = false Then
MessageBox.Show("Please enter a valid Number")
Exit Sub
End If
' Code if Data was entered properly
End Sub
IsNumeric Function - Description
Data Validation: The process of verifying that all user entries are valid.
One goal of this verification is to prevent runtime errors.
The IsNumeric function tests whether the value of an expression is numeric.
The function returns a Boolean value, which can be tested in a conditional expression.
If the Boolean value is true, the expression is numeric.
The IsNumeric function treats both positive and negative numbers as valid.
The IsNumeric function treats both numbers with and without decimal places as valid.
Figure UDDT-2: General Syntax and Example for IsNumeric Function
Help Support this site - Click this ad
Armed with all this knowledge, it looks like we are ready to tackle the next challenge:
Design a VisualBasic.NET project to store the following data about students in a class. The data includes
the student's last name, first name, student id, and GPA. Allow the user to enter the data for each student followed by a click on a Button so store the data
in a dynamic array of structures. Add Buttons to display:
Enter the student data.
Display the student data in a listbox.
Compute the class average GPA.
End Program Execution.
Perform a search based on the Student - ID.
Use an Input Box function to get the student's ID.
Write a general function to validate the input data before processing. The validation rules are:
Last Name must exist.
First Name must exist.
Student ID must be in the form: ###-##-####.
the GPA must be a number between 0 and 4.
Based on the preceding specifications, the following diagram is one possible configuration:
Figure Structure-1: Student Data Form Design
Help Support this site - Click this ad
Enter the following code into your Visual Basic Source Code (Form) Window:
Public Class Form1
Private Structure StudentRecord
Dim LastName As String
Dim FirstName As String
Dim ID As String
Dim GPA As Double
End Structure
Dim Student() As StudentRecord
Dim StudentIndex As Integer
' AddEntry transfers the data in the TextBoxes on the Form
' To the Next Student Record Structure
Private Sub AddEntry(ByVal Index As Integer)
Dim DataString As String
Dim FullName As String
FullName = Student(Index).LastName + ", " + _
Student(Index).FirstName
DataString = FullName.PadRight(20) + _
Student(Index).ID.PadRight(14) + _
Student(Index).GPA.ToString(".00")
lstDisplay.Items.Add(DataString)
End Sub
'Sub to Validate proper Entry format on the form
Private Sub ValidateData()
Dim LastName As String
LastName = txtLastName.Text
If LastName = "" Then
MessageBox.Show("Please Enter the Student's Last Name")
txtLastName.Clear()
txtLastName.Focus()
Exit Sub
End If
Dim FirstName As String
FirstName = txtFirstName.Text
If FirstName = "" Then
MessageBox.Show("Please Enter the Student's First Name")
txtFirstName.Clear()
txtFirstName.Focus()
' Me.ActiveControl = txtFirstName
Exit Sub
End If
Dim StudentID As String
Dim IDComponents() As String
StudentID = txtStudentID.Text
IDComponents = StudentID.Split("-")
If IDComponents.Length <> 3 Or _
IDComponents(0).Length <> 3 Or _
IDComponents(1).Length <> 2 Or _
IDComponents(2).Length <> 4 Or _
IsNumeric(IDComponents(0)) = False Or _
IsNumeric(IDComponents(1)) = False Or _
IsNumeric(IDComponents(2)) = False Then
MessageBox.Show("Please enter ID in proper Format: ###-##-####")
txtStudentID.Clear()
txtStudentID.Focus()
Me.ActiveControl = txtStudentID
Exit Sub
End If
Dim strGPA As String
strGPA = txtStudentGPA.Text
If IsNumeric(strGPA) = False Then
MessageBox.Show("Please Enter a Grade Point Average Number between 0 and 4.0")
txtStudentGPA.Clear()
txtStudentGPA.Focus()
Me.ActiveControl = txtStudentGPA
Exit Sub
End If
Dim dblGPA As Double
dblGPA = CDbl(strGPA)
If dblGPA < 0 Or dblGPA > 4 Then
MessageBox.Show("Please enter a Grade Point Average Number between 0 and 4.0")
txtStudentGPA.Clear()
txtStudentGPA.Focus()
Me.ActiveControl = txtStudentGPA
Exit Sub
End If
ReDim Preserve Student(StudentIndex)
Student(StudentIndex).LastName = LastName
Student(StudentIndex).FirstName = FirstName
Student(StudentIndex).ID = StudentID
Student(StudentIndex).GPA = dblGPA
AddEntry(StudentIndex)
StudentIndex += 1
End Sub
'Event Generated by Clicking on the ListBox
Private Sub lstDisplay_SelectedIndexChanged(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles lstDisplay.SelectedIndexChanged
Dim Index As Integer
Index = lstDisplay.SelectedIndex
DisplaySelectedStudent(Index)
End Sub
'Sub to transfer data from Structure element to Form TextBoxes
Private Sub DisplaySelectedStudent(ByRef Index As Integer)
txtFirstName.Text = Student(Index).FirstName
txtLastName.Text = Student(Index).LastName
txtStudentID.Text = Student(Index).ID
txtStudentGPA.Text = Student(Index).GPA.ToString(".00")
End Sub
' Event Generated when Clear Button Is pressed
Private Sub txtLastName_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles txtLastName.Click
ClearTextFields()
End Sub
'Sub to clear all TextBoxes at once.
Private Sub ClearTextFields()
txtFirstName.Clear()
txtStudentID.Clear()
txtLastName.Clear()
txtStudentGPA.Clear()
txtLastName.Focus()
End Sub
'Event Generated when Exit Button is pressed
Private Sub btnExit_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnExit.Click
Me.Close()
End Sub
'Event Generated by Pressing Calculate Class GPA Button
Private Sub btnAverageGPA_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnAverageGPA.Click
Dim Index As Integer
Dim Sum As Double
Dim Ave As Double
For Index = 0 To StudentIndex - 1
Sum += Student(Index).GPA
Next
If StudentIndex > 0 Then
Ave = Sum / StudentIndex
End If
txtAverageGPA.Text = "Class Ave = " + Ave.ToString(".00")
End Sub
' Event Generated when Enter Button is pressed
Private Sub btnEnter_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnEnter.Click
ValidateData()
txtAverageGPA.Clear()
ClearTextFields()
End Sub
' Event Generated when Search Button is pressed
Private Sub btnSearch_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnSearch.Click
Dim ID As String
Dim Index As Integer
Dim MatchFound As Boolean = False
ID = InputBox("Please Enter the Student's SSN (ID)", "Student Search")
If ID <> "" Then
For Index = 0 To StudentIndex - 1
If ID = Student(Index).ID Then
DisplaySelectedStudent(Index)
MatchFound = True
End If
Next
End If
If MatchFound = False Then
MessageBox.Show("No Match Found for " + ID)
ClearTextFields()
End If
End Sub
' Event Generated by Pressing the Display Button
Private Sub btnDisplay_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnDisplay.Click
lstDisplay.Items.Clear()
Dim Index As Integer
For Index = 0 To StudentIndex - 1
AddEntry(Index)
Next
End Sub
End Class
Figure Structure-2: Source Code for Example 1
Help Support this site - Click this ad
The function of the code is outlined below. Program statements are in bold,
Comments are in blue and explanations are in normal text:
Declare and Define Structure of Type StudentRecord:
Private Structure StudentRecord:
Private: Visual Basic Structures may only be Public or Private.
Since this is a single form project either option is adequate.
Structure: Visual Basic Keyword used to declare a structure. The formal syntax is stated above.
Student Record: This is the name the programmer, you in this case, gives to give to refer to the structure.
Visual Basic will accept nearly any name you give it. But, it is easier to remember if it describes the structure.
MonkeyFeet would work, but it doesn't describe students very well.
Dim LastName As String: This is the variable we are going to pull from the txtLastName ListBox Control.
Dim FirstName As String: This is the variable we are going to pull from the txtFirstName ListBox Control.
Dim ID As String: This is the variable used to reference the student's Social Security Number.
Dim GPA As Double: This variable will reference the student's GPA.
End Structure: You have to tell Visual Basic you are done defining the structure.
The Visual Basic IDE is pretty good at guessing what you want, but you still have to tell it a lot of what you want.
Declare Array of Structures and Size of Array Variable(StudentIndex)
Dim Student() As StudentRecord:
Dim: Since we are declaring Student() outside a function, it is the same as declaring Private.
Student(): We are now declaring an Array that we will later refer to as Student.
At this point, Student() is unusable because it is an array with no elements.
If you try to use it, you will get a RUN-TIME ERROR and the program will halt.
You must either use a ReDim or ReDim Preserve with a value between the parentheses.
Example: ReDim Preserve Student(50):
To access one of your 50 student records, use the '.' dot operator.
Example: Student(5).LastName is the last name of student #5.
As StudentRecord: This is the new Data Type we have defined by using the Structure keyword.
Dim StudentIndex As Integer: This is going to be the counter for how many student records have been entered.
You could also call this NumberOfStudents if that makes more sense to you.
Help Support this site - Click this ad
Sub AddEntry is used to transfer data from the TextBoxes on the Form onto the display.
Private Sub AddEntry(ByVal Index As Integer):
Sub Declaration for AddEntry
Index As Integer: Student Structure Array Index.
Dim DataString As String: Building block to create entry for ListBox lstDisplay.
Dim FullName As String: A new variable used to put the first and last names together.
FullName.PadRight(20): Make the name 20 characters long so it lines up well in the ListBox lstDisplay.
Courier New is a "Fixed Width Font" if you are making tables where you want everything to line up.
You should change the Font in the ListBox lstDisplay so the columns line up.
Student(Index).ID.PadRight(14): The SSN is always 11 characters wide, so this will give 3 blank spaces to the right.
Student(Index).GPA.ToString(".00"): This will give two places to the right of the decimal.
We do not need to PadLeft because we will always have 1 place to the left of the decimal (0-4).
lstDisplay.Items.Add(DataString): This immediately adds the entry to the ListBox.
This is optional - since we have a Display Button.
Placing this statement here makes the the Display Button irrelevant.
In order to continue with this guide, complete explanation of this example, and cover many
other breathtaking examples, press the
Press the Button below: