Hot-Link Menu in Right-Side Column

Last Updated 6-30-2010


 
MoreNetbooks.php
  • More Computers
  •  
    MorepcGames.php
  • More Games
  •  
    MoremobileBroadband.php
  • More Electronics
  •  
    MoreScienceBooks.php
  • More Books
  •  
    MoreProgramming.php
  • More Software
  • Visual Basic Parallel Arrays

    That was fun, but what would really be lots more fun would be to see the name of the person associated with the score. That way, if their score is lower than ours, we can poke fun at them. But, we need to stay clear of that clown with the highest score.

    Example 5

    This time design a Visual Basic.NET program to display the name as well as the score. In a manner similar to the example above:

    • This time associate the name of the student with their score.
    • Enter scores between 0 and 100.
    • Display the min and max values with the student's name
      • So we can see who to make fun of, and who to avoid.

    The following diagram illustrates 1 possibility of the form at design time:

    Ex 5 Form Design

    Figure Array-11: Example 5 Form at Design Time


    Buy from Centurion


    The following diagram is the same form with the controls desginated by their name property:

    Ex 5 Form Design Expanded

    Figure Array-12: Example 5 Form at Design Time Expanded


    Help Support this site - Click this ad

    With the form designed, and all the controls given their name properties, enter the following code in the VB.Form tab:

    
    Public Class Form1
    
    'Declare Array Visible to Entire Class
    
    Private NumberOfScores As Integer = 0
    Private MaxEntries As Integer = 20
    Private ScoreArray(MaxEntries ) As Double 
    Private NameArray(MaxEntries ) As String 
    
    'Enter Student Name - press <Enter> to place value into Array
    
    Private Sub txtStudentName_Enter (ByVal sender As System .Object , _
            ByVal e As KeyEventArgs) Handles txtStudentName .KeyDown 
    
            Dim NameEntered As String 
    
            If e.KeyCode = keys.Enter then
    
                NameEntered = txtStudentName .Text 
                If NameEntered = "" then
                    MessageBox .Show ("You must enter a Name")
                    txtStudentName .Focus 
                    Exit Sub 
                End If
                NameArray (NumberOfScores)=NameEntered 
                txtMidtermScore.Clear 
                txtMidtermScore.Focus 
            End If
    
    End Sub 
    
    
    'Enter scores - press  to place value into Array
    
    Private sub   txtQuizScore_Enter (ByVal sender As System .Object , _
            ByVal e As KeyPressEventArgs ) Handles txtMidtermScore.KeyPress
    
        
        Dim EnteredValue As Double 
        Dim DataString As String 
    
        If e.KeyChar = ControlChars.Cr  Then
        
            If Double .TryParse (txtMidtermScore .Text ,EnteredValue  ) = False then
                MessageBox .Show (" You must enter a numeric value like 1 or 2")
                txtMidtermScore .Clear 
                txtMidtermScore .Focus 
                Exit Sub 
            End If
    
            If EnteredValue  < 0 or EnteredValue  >100 then
                MessageBox .Show ("Valid range is between 0 and 100, 7 would work " _
                    & EnteredValue .ToString  & " Does not")
                txtMidtermScore .Clear 
                txtMidtermScore .Focus
                Exit Sub  
            End If
    
            If NumberOfScores < MaxEntries then
                ScoreArray (NumberOfScores) = EnteredValue 
              
                DataString = (NumberOfScores+1) .ToString + ".  " + _
                    NameArray (NumberOfScores).PadRight (15) + _
    			EnteredValue  .ToString.PadLeft (5) 
                lstDisplay.Items.Add (DataString )
                NumberOfScores += 1
            End If
            txtMidtermScore .Clear 
            txtStudentName .Clear 
            txtStudentName  .Focus 
            Exit Sub 
        End If 
    
    ' Handles user entering a <TAB> key
    
        If NameArray (NumberOfScores) = "" then
            If txtStudentName.Text <> "" then
                NameArray (NumberOfScores) = txtStudentName .Text 
    
            Else
                MessageBox.Show ("you must enter the name first")
                txtMidtermScore .Clear 
                txtStudentName .Clear 
                txtStudentName .Focus 
            End If
        End If
    
    End Sub 
    
    'Clear Last Entry
    
    Private Sub btnClearLast_Click( ByVal sender As System.Object,  _
    	ByVal e As System.EventArgs) Handles btnClearLast.Click
        NumberOfScores -= 1
        lstDisplay .Items .RemoveAt (NumberOfScores )
        txtMidtermScore .Clear 
        txtStudentName  .Clear 
        txtStudentName  .Focus 
        
    End Sub
    
    'Clear All Entries
    
    Private Sub btnClearAll_Click( ByVal sender As System.Object,  _
    	ByVal e As System.EventArgs) Handles btnClearAll.Click
        lstDisplay .Items .Clear 
        NumberOfScores = 0
        txtMidtermScore .Clear 
        txtStudentName  .Clear 
        txtStudentName .Focus 
    End Sub
    
    'Calculate Min, Max and Average
    
    Private Sub btnStatistics_Click( ByVal sender As System.Object,  _
    	ByVal e As System.EventArgs) Handles btnStatistics.Click
        Dim Output As String 
        Dim Average As Double = 0
        Dim Sum As Double = 0
        Dim ScoreNumber As Integer 
        Dim MinScore As Double = ScoreArray (0)
        Dim MaxScore As Double = ScoreArray (0)
    
        lstDisplay .Items .Add ("")
    
        For ScoreNumber =0 to NumberOfScores - 1
            Sum+=ScoreArray (ScoreNumber)
            If(MinScore > ScoreArray (ScoreNumber) ) then
                MinScore = ScoreArray (ScoreNumber)
            End If
            If(MaxScore < ScoreArray (ScoreNumber)) then
                MaxScore = ScoreArray (ScoreNumber)
            End If
        Next
    
    
        If(NumberOfScores>0 ) then
            Average = Sum/NumberOfScores
        End If
        
    
        Output ="Average: " + Average .ToString(".0")
    
        lstDisplay .Items .Add (Output )
        Output ="Minimum: " + MinScore .ToString 
        lstDisplay .Items .Add (Output )
        Output ="Maximum: " + MaxScore .ToString 
        lstDisplay .Items .Add (Output )
    
        txtMidtermScore .Clear 
        txtStudentName .Clear 
        txtStudentName .Focus 
        
        
    End Sub
    
    'Set the focus to the Student Name at Run Time
    
    Private Sub Form1_Load( ByVal sender As System.Object,  ByVal e As System.EventArgs) _
        Handles MyBase.Load
        
        Dim MessageString As String 
        
        Me.ActiveControl=txtStudentName 
    
        MessageString = "First, Enter the student Name and Press , " +vbCrLf 
        MessageString += "then enter the student score and Press " +vbCrLf
        MessageString += "The Name and Score will be displayed in the Score Display"
    
        MessageBox.Show (MessageString)
    
        
    End Sub
    End Class
    						

    Figure Array-13: Example 5 Source Code.


    Help Support this site - Click this ad

    There are a couple of new concepts introduced in this code section:

    • Private NumberOfScores As Integer = 0: Initialize the array index to 0
    • Private MaxEntries As Integer = 20: This will be the maximum size of the array.
      • Larger arrays will be declared dynamically, since this is just an example - fixed size is okay.
    • Private ScoreArray(MaxEntries ) As Double: This is the array containing the numeric data of students course scores.
    • Private NameArray(MaxEntries ) As String: This is the parallel array containing the names of the students in the course.

    • Student name uses KeyEventArgs while Midterm Score optionally uses KeyEventPressArgs.

    • Private Sub txtStudentName_Enter (ByVal sender As System .Object , ByVal e As KeyEventArgs) Handles txtStudentName .KeyDown
      • Private Sub txtStudentName_Enter: This is the routine that is called every time a key is pressed in the student name TextBox, txtStudentName, each time checking for the <Enter> key to be pressed.
      • ByVal sender as System.Object: Sender is Visual Basic's reference to the TextBox control.
      • ByVal e as KeyEventArgs: e is the key information occuring every time a key is detected in the down position.
      • Handles txtStudentName.KeyDown: This is the routine to be called when Windows detects a Key in the txtStudentName control.

    • Private sub txtMidtermScore_Enter (ByVal sender As System.Object, ByVal e As KeyPressEventArgs) Handles txtMidtermScore.KeyPress
      • Private sub txtMidTermScore_Enter: This function will be called when the <Enter> key is pressed in the TextBox.
      • ByVal sender As System.Object: A reference to the TextBox control.
      • ByVal e As KeyPressEventArgs e is every key pressed. KeyPressEventArgs decodes which key is pressed.
      • Handles txtMidTermScore.KeyPress: Call this subroutine after every key press in the MidtermScoreTextBox.

    • Dim EnteredValue As Double: This will be the numeric variable which receives the number entered in the textbox.
    • Dim DataString as String: A String used to build a reflection of the data entered to be displayed in the ListBox.

    • If e.KeyChar = ControlChars.Cr Then: Test for <Enter> key.
      • e.KeyChar: The last key pressed in the TextBox.
        • e: is the key pressed on the keyboard.
        • KeyChar: is used as the reference in the KeyPressEventArgs class descriptor.
      • ControlChars.Cr The comparison value for the <Enter> key when using KeyPressEventArgs.
        • ControlChars: is used to decode KeyChar.
        • Cr: is the value associated with the <Enter> key.

    • If Double .TryParse (txtQuizScore .Text ,EnteredValue ) = False then: Check for Numeric Value.
      • Double.TryParseSearch the text for a value of type double.
      • txtMidtermScore.Text: The text is the Quiz Score TextBox is what will be scanned for a numeric value.
      • EnteredValue: The recipient of the Double value if the scan is successful.
      • =False then: Text was in improper format - execute code on next line.
    • MessageBox .Show (" You must enter a numeric value like 1 or 2"): Display a message box gently guiding the user to the correct response.
    • txtMidterm .Clear: Remove the information that was previously in the TextBox.
    • txtMidtermScore.Focus: Place the Cursor in the empty TextBox, so they start right in entering data.
    • Exit Sub: Error in Data Entry, no point in going any further.
    • End If: End of Data Entry check for non-numeric value.

    • If EnteredValue < 0 or EnteredValue >10 then: Check for valid range between 0 and 10.
    • If NumberOfScores < MaxEntries then: Make sure they aren't getting too ambitious, and going out of bounds on the array.
    • ScoreArray (NumberOfScores) = EnteredValue: All is good, place value in next array location.
    • DataString = (NumberOfScores+1).ToString + ". "+NameArray(NumberOfScores).PadRight(15)+EnteredValue.ToString.PadLeft(5):
      • DataString=(NumberOfScores+1).ToString+". ": Enumerate the entry.
      • +NameArray(NumberOfScores).PadRight(15): Make Name be 15 spaces with blank spaces to the right.
      • +EnteredValue.ToString.PadLeft(5): Create string echoing number entered but 5 spaces wide.
    • lstDisplay.Items.Add (DataString ): Visual Basic syntax to place data at the end of the ListBox display.
    • NumberOfScores+=1 Move to Next array location.
    • txtMidtermScore.Clear: Clear the Midterm Score TextBox.
    • txtStudentName .Clear: Clear the Student Name TextBox.
    • txtStudentName .Focus: Set the cursor in the Student Name TextBox.
    • Exit Sub: It is important to not do the following Tab Check.

    • Help Support this site - Click this ad

    • This section checks for a <TAB> key which is handled differently by Visual Basic

    • If NameArray (NumberOfScores) = "" then: Check to see if the student name was processed.
    • If txtStudentName.Text <> "" then: If the student name textbox is not empty - tab was pressed.
    • NameArray (NumberOfScores) = txtStudentName .Text: Save the contents of the textbox into the array of names.

    • Else: You are here if the name TextBox was left empty.

    • MessageBox.Show ("you must enter the name first"): Instruct the user
    • txtMidtermScore .Clear: Clear what was in the score.
    • txtStudentName .Clear: Clear anything that was in the student name.
    • txtStudentName .Focus: Place the cursor back in the student name TextBox


    • This SUB clears the last entry out of the ListBox.

    • Private Sub btnClearLast_Click( ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClearLast.Click.
      • Visual Basic generated code to respond to the Clear Last Entry button being pressed.

    • NumberOfScores -= 1: Reset Array index to last entry entered.
    • lstDisplay .Items .RemoveAt (NumberOfScores ): Remove the Last Entry.
    • txtMidtermScore.Clear: Clear the Midterm score textbox.
    • txtStudentName.Clear: Clear the Student name textbox.
    • txtStudentName.Focus: Place the cursor in the student name textbox.


    • This Clears All Display Controls and sets the Focus on the Student Name.

    • Private Sub btnClearAll_Click( ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClearAll.Click.
      • Visual Basic Generated code to respond to the Clear All button being pressed.

    • lstDisplay .Items .Clear: Syntax to clear a ListBox.
    • NumberOfScores=0: Effectively clear the array by resetting the index to 0.
    • txtMidtermScore.Clear: Clear the data entry TextBox.
    • txtStudentName.Clear: Clear student name text box.
    • txtStudentName.Focus: Set the cursor in the Student Name TextBox.


    • Help Support this site - Click this ad

    • This Sub calculates Minimum, Maximum and Average Midterm Scores

    • Private Sub btnStatistics_Click( ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStatistics.Click.
      • Visual Basic generated code to respond to the Statistics button being pressed.
    • Dim Output As String: Workhorse variable to prepare text to send out to ListBox display.
    • Dim Average As Double = 0: Preset the Average variable to 0 for clarity.
    • Dim Sum As Double = 0: The sum must start at 0, in order for the average calculation to work.
    • Dim ScoreNumber as Integer: Variable used to index through the Scores array.
    • Dim MinScore As Double = ScoreArray (0): Set the minimum value to the first value in the array.
    • Dim MinScore As Double = ScoreArray (0): Set the maximum value to the first value in the array.
    • lstDisplay .Items .Add (""): Add in a blank line in the ListBox display.
    • For ScoreNumber =0 to NumberOfScores - 1: Create For Loop to index through all Quiz Scores entered.
    • Sum+=ScoreArray (ScoreNumber): Sum each score in the array.
    • If(MinScore >ScoreArray (ScoreNumber) ) then: Check if the present score is lower than the previous minimum value.
    • MinScore = ScoreArray (ScoreNumber): Set New Minimum if lower.
    • If(MaxScore < ScoreArray (ScoreNumber)) then: Check if the present score is higher than the previous maximum value.
    • MaxScore = ScoreArray (ScoreNumber): Set the New Maximum if higher.
    • If(NumberOfScores>0 ) then: Check to make sure we don't get a /0 error.
    • Average = Sum/NumberOfScores: Calculate the average.
    • Output ="Average: " + Average .ToString: Create text to output Average.
    • lstDisplay .Items .Add (Output ): Display the Average.
    • Output ="Minimum: " + MinScore .ToString: Create and Display Minimum value.
    • Output ="Maximum: " + MaxScore .ToString: Create and Display Maximum value.


    • The FormLoad sub is used to set the focus on the student's name at Run Time

    • Private Sub Form1_Load( ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    • Me.ActiveControl=txtStudentName: Set the focus on a control when the form loads in Visual Basic .NET
      • Me: refers to the active form
      • ActiveControl: The control which gets the focus and becomes active.
      • txtStudentName The textbox where the student name is entered.

    In order to continue this guide and work on that even more fascinating topic Dynamic Arrays press the Button Below:


    Help Support this site - Click this ad

    Home


    Visual Basic

    Introduction to VB.NET

    .NET Framework

    VS2008 IDE

    How VB is Compiled

    Start Visual Studio


    Windows Form App


    Save Your Work

    VB OOP Programming

    Visual Basic Code


    Exit Code


    Button Event Code

    Coding Recommendations

    If/Then/Else

    Error List Window

    Comment Syntax

    Help Window

    Language Essentianl

    Built-In Data Types


    Declare Variables

    Declare Constants

    Code Arithmetic Expressions

    Assignment Statements

    Operator Precedence

    Type Casting


    Math Class

    String Declaration

    Conversion Functions

    Conversion Methods

    Formatting Functions

    String Formatting


    Variable Scope

    Enumerations

    Nullable Types


    Loop Constructs

    For Next Loop

    Do While Loop


    Do Until Loop

    Do...Loop-While

    Do...Loop-Until


    Exit Do | Exit For

    Do...Loop


    Nested Loops


    Arrays

    Array Declaration


    Rnd( ) Function

    Listbox Control


    KeyPressEventArgs


    Parallel Arrays

    Key Event Args


    Dynamic Arrays

    Redimension Array

    Set Breakpoint

    Start Debugger


    ReDim Preserve


    MultiDimensional Arrays

    DataGridView Control


    Length and Sort Methods


    Structures

    Pad Right

    Split Method

    IsNumeric Function


    Multiform Projects


    Add Form To Project

    Form Object Methods

    Form Show Method

    ShowDialog Method

    Form Close Method

    Form Accept Button

    Multiform Project Example


    ASP.NET Web Programming

    Create Data Source


    Configure Access Data Source


    Add Product Class


    Extract Local Database Data

    Order PageLoad VB Code

    Add New Web Page


    Set Start Page

    Display Cart Aspx Code

    Display Cart Design View

    Sorted List Definition

    VB.NET Session State


    Create CartItem Class

    GetCartContents Function


    Add To Cart Event Handler

    Remove Cart Item Event


    Clear Cart Event Handler