locked
Visual Basic "On Error GoTo" RRS feed

  • Question

  • I have created a program in Visual Basic code, how do I add unstructured exception handling into the program using "On Error GoTo" to pick up errors such as the text boxes being left blank?
    Saturday, June 1, 2013 12:02 PM

Answers

  • You don't. On Error Goto is a hang over from VB6 (and earlier versions). You should test the values of the text boxes (with if...else...) or use validation events. You could also use key events (press or up) to prevent invalid chars.

    Regards David R
    ---------------------------------------------------------------
    The great thing about Object Oriented code is that it can make small, simple problems look like large, complex ones.
    Object-oriented programming offers a sustainable way to write spaghetti code. - Paul Graham.
    Every program eventually becomes rococo, and then rubble. - Alan Perlis
    The only valid measurement of code quality: WTFs/minute.

    • Proposed as answer by Cor Ligthert Saturday, June 1, 2013 1:25 PM
    • Marked as answer by Youen Zen Thursday, June 20, 2013 8:13 AM
    Saturday, June 1, 2013 12:27 PM

All replies

  • Hello,

    The idea should be to use assertion for things like TextBox controls left blank ie. Before using data in TextBox make sure it has data then if we want to use it as an integer we first check if the data in the TextBox can be used as a valid integer.

    Private Sub Button1_Click( _
        ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Button1.Click
        If Not String.IsNullOrEmpty(TextBox1.Text) Then
            ' Do something
            Dim Value As Int32 = 0
            If Int32.TryParse(TextBox1.Text, Value) Then
                ' Okay to use Value as an integer
            Else
                ' TextBox could not be converted to an integer.
            End If
        Else
            ' Nothing to work with in TextBox
        End If
    End Sub

    If there is a chance of something that you did not count on happened use Try/Catch and also Unhandled exception handler, never use On Error Go To, this is VB6 style of coding and is not the way to go.

    This can be taken to another level with Code contracts and unit testing.


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem.

    Saturday, June 1, 2013 12:27 PM
  • You don't. On Error Goto is a hang over from VB6 (and earlier versions). You should test the values of the text boxes (with if...else...) or use validation events. You could also use key events (press or up) to prevent invalid chars.

    Regards David R
    ---------------------------------------------------------------
    The great thing about Object Oriented code is that it can make small, simple problems look like large, complex ones.
    Object-oriented programming offers a sustainable way to write spaghetti code. - Paul Graham.
    Every program eventually becomes rococo, and then rubble. - Alan Perlis
    The only valid measurement of code quality: WTFs/minute.

    • Proposed as answer by Cor Ligthert Saturday, June 1, 2013 1:25 PM
    • Marked as answer by Youen Zen Thursday, June 20, 2013 8:13 AM
    Saturday, June 1, 2013 12:27 PM
  • If you are using a winform, then consider using an errorprovider. http://msdn.microsoft.com/en-us/library/system.windows.forms.errorprovider.aspx

    -----
    MrStu

    Saturday, June 1, 2013 1:01 PM
  • Do not use On Error Goto.  Do something like this instead:

    If Textbox1.Text = "" Then

        MessageBox.Show("Please enter data in textbox.")

        Textbox1.Focus()

        Exit Sub

    End If


    Solitaire

    Saturday, June 1, 2013 4:16 PM
  • I have created a program in Visual Basic code, how do I add unstructured exception handling into the program using "On Error GoTo" to pick up errors such as the text boxes being left blank?

    Who came up with an "On Error Go To" idea? Why not just handle the error at that point?

    Option Strict On
    
    Public Class Form1
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Me.Text = "Error Testing"
        End Sub
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            If TextBox1.Text <> "" And TextBox2.Text <> "" And TextBox3.Text <> "" And TextBox4.Text <> "" Then
                TextBox5.Text = (CInt(TextBox1.Text) + CInt(TextBox2.Text) + CInt(TextBox3.Text) + CInt(TextBox4.Text)).ToString
            Else
                MessageBox.Show("One of the TextBox's is empty. Please fill it in and try again.")
                Exit Sub
            End If
    
            MessageBox.Show("More stuff to do here if the above worked")
    
        End Sub
    
        Private Sub TextBox_TextChanged(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress, TextBox2.KeyPress _
            , TextBox3.KeyPress, TextBox4.KeyPress
    
            If ("0"c <= e.KeyChar AndAlso e.KeyChar <= "9"c) Or e.KeyChar = Chr(8) Or e.KeyChar = Chr(13) Then
                e.Handled = False
                MyBase.OnKeyPress(e)
            Else
                e.Handled = True
                MyBase.OnKeyPress(e)
            End If
        End Sub
    
    End Class
    


    You've taught me everything I know but not everything you know.

    Saturday, June 1, 2013 9:32 PM
  • John,

    Use your program there and type in a letter in one of the TextBoxes.

    Think there's a problem?


    Please call me Frank :)

    Saturday, June 1, 2013 9:37 PM
  • Are you referring to TextBox5? If so I just added this to the Form Load event.

    TextBox5.Enabled = False
    TextBox5.BackColor = Color.White


    You've taught me everything I know but not everything you know.

    Saturday, June 1, 2013 9:52 PM
  • Are you referring to TextBox5? If so I just added this to the Form Load event.

    TextBox5.Enabled = False
    TextBox5.BackColor = Color.White


    You've taught me everything I know but not everything you know.

    No, this part (as one example):

    TextBox5.Text = (CInt(TextBox1.Text)

    What happens if the text in TextBox1 is a character (or anything that cannot be converted to an integer)?


    Please call me Frank :)

    Saturday, June 1, 2013 9:54 PM
  • If data input can be a string, then use this code to verify that all textboxes are filled:

        Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
            Dim notdone As Boolean = False
            For Each txt As TextBox In Me.Controls.OfType(Of TextBox)().Reverse
                  If txt.Text = "" Then
                    txt.Focus()
                    MessageBox.Show("Required entry in " & txt.Name)
                    notdone = True
                    Exit For
                End If
            Next txt
            If notdone = False Then MessageBox.Show("All entries complete", "OK")
        End Sub

    If data must be numeric, then use the following code for required integers.  It will also detect empty strings.  If data must be type Double or Decimal, then make the appropriate changes as indicated:

        Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
            Dim notdone As Boolean = False
            Dim testint As Integer = 0      'or change to Double or Decimal if required by input data
            For Each txt As TextBox In Me.Controls.OfType(Of TextBox)().Reverse
                If Not Integer.TryParse(txt.Text, testint) Then     'change to Double or Decimal if required
                    txt.Focus()
                    MessageBox.Show("Required correct entry in " & txt.Name)
                    txt.Text = ""   'in case of non-numeric entry
                    notdone = True
                    Exit For
                End If
            Next txt
            If notdone = False Then MessageBox.Show("All entries complete", "OK")
        End Sub

    Note:  The above code will check for every textbox on a form.  If you need to test selected textboxes, then you should put them inside a container, or use the Tag property, changing one line in the above code as follows:

    If txt.Text = "" AndAlso txtTag Is "whatever" Then  'etc.

    or

    If Not Integer.TryParse(txt.Text, testint) AndAlso txt.Tag Is "whatever" Then   'etc.


    Solitaire


    • Edited by Solitaire Saturday, June 1, 2013 11:11 PM
    Saturday, June 1, 2013 11:03 PM
  • I think the .Validating event is a better approach, but to each their own.

    Using that event, as soon as the control first has and then later loses focus, you can then immediately lock them into that control until they've made the entry valid. Further, you can also validate limits (for instance, maybe the number must be greater than some value, etc.).

    That said, I also first test that the TextBox isn't empty. That's their way out of the 'locked in' status in case they simply don't know.

    Then use the TextBox's .TextChanged event to handle whether or not they can proceed (for example, disabling the button that's to be clicked to show the result).

    For what it's worth ...


    Please call me Frank :)

    Saturday, June 1, 2013 11:12 PM
  • "Who came up with an "On Error Go To" idea? Why not just handle the error at that point?"

    A long time ago, prior to structured code there were "On error Goto's". In a structured sense, your second question makes much, much sense.

    Renee


    "MODERN PROGRAMMING is deficient in elementary ways BECAUSE of problems INTRODUCED by MODERN PROGRAMMING." Me

    Saturday, June 1, 2013 11:56 PM
  • Who came up with an "On Error Go To" idea? Why not just handle the error at that point?

    Perhaps the error could not be picked up before it occurred, such as if the USB stick is removed in the middle of accessing a file.

    On Error Goto had its correct usage in VB6, just as Try/Catch does in the framework.

    Sunday, June 2, 2013 1:08 AM

  • On Error Goto had its correct usage in VB6, just as Try/Catch does in the framework.

    Every version of VB even VBA and VBS not only VB6.

    However, I miss the part where this helps the OP.

    The Try Catch is just a newer way, more usable in modern programming and then not only VB which has proven to give for instance better maintenance on code.

      However, I see no replies from the OP, so it is even possible he had meant his question for an older version of VB, VBA or VBS. 

    There is currently a bug in the forums which it makes impossible for non moderators to unpropose answers. So maybe a moderator can do that. And because of the fact the question is as long as the OP does not reply not a question for the topic of this forum to move it to Off Topic.


    Success
    Cor


    Sunday, June 2, 2013 9:32 AM