Jump to content

Talk:Visual Basic .NET/Reusable Code

Page contents not supported in other languages.
Add topic
From Wikiversity

Example code for the exercise

[edit source]

The code below is only one way to have completed the exercise.

    Public strValidChars As String = "1234567890".ToCharArray & Chr(20) 'Includes backspace "character"

    Private Sub txtInputOutput_KeyPress(ByVal sender As Object, _
                                        ByVal e As System.Windows.Forms.KeyPressEventArgs) _
                                        Handles txtInput.KeyPress, txtOutput.KeyPress
        'If the entered character is not one of the valid chars then disregard
        If Not strValidChars.Contains(e.KeyChar) Then
            e.KeyChar = Nothing
            e.Handled = True
        End If
        e.Handled = False
    End Sub

    Private Sub btnTimesTwo_Click(ByVal sender As System.Object, _
                                  ByVal e As System.EventArgs) _
                                  Handles btnTimesTwo.Click
        'convert the input to integer then send to multiply function and 
        'assign the return to the output
        Try
            txtOutput.Text = MultiplyMyInput(CInt(txtInput.Text), 2)
        Catch ex As Exception
            MsgBox("Input too large for integer datatype")
        End Try
    End Sub

    Private Sub btnTimesFour_Click(ByVal sender As System.Object, _
                                   ByVal e As System.EventArgs) 
                                   Handles btnTimesFour.Click
        'convert the input to integer then send to multiply function and 
        'assign the return to the output
        Try
            txtOutput.Text = MultiplyMyInput(CInt(txtInput.Text), 4)
        Catch ex As Exception
            MsgBox("Input too large for integer datatype")
        End Try
    End Sub

    Private Function MultiplyMyInput(ByVal Input As Integer, _
                                     ByVal Mult As Integer) As Integer
        Dim Output As Integer
        'Multiply the input to get the output.  If too big, display an error message and return 0
        Try
            Output = Input * Mult
        Catch ex As Exception
            MsgBox("Result too large for integer datatype.")
            Return 0
        End Try
        Return Output
    End Function