none
how can i clear just the error input with try catch

    Question

  • here is the code, i want to clear just the box with the error in it. if possible and leave the other numbers in put as they where.
      Private Sub btnCalc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalc.Click
    
        ' the following declare the values that will be used
    
        Dim dblScore1 As Double
        Dim dblScore2 As Double
        Dim dblScore3 As Double
        Dim dblScore4 As Double
        Dim dblScore5 As Double
        Const dblSubtotal As Double = 5
        Dim dblAverage As Double
    
    
    
        ' here we try for errors and compile the code for the operation
    
        Try
    
          ' The following will take the text and convert to a decimal to be used in the calculation
    
          dblScore1 = CDbl(txtScore1.Text)
          dblScore2 = CDbl(txtScore2.Text)
          dblScore3 = CDbl(txtScore3.Text)
          dblScore4 = CDbl(txtScore4.Text)
          dblScore5 = CDbl(txtScore5.Text)
    
          ' this line will perform the calculation
    
          dblAverage = ((dblScore1 + dblScore2 + dblScore3 + dblScore4 + dblScore5) / dblSubtotal)
    
          ' This line Outputs the calculation to the form
          lblAverage.Text = dblAverage.ToString
    
        Catch ex As Exception
    
          ' this line opens an error box asking for numbers only
    
          MessageBox.Show("numbers only please")
    
          ' This line clears the text boxes of data
    
          txtScore1.Clear()
          txtScore2.Clear()
          txtScore3.Clear()
          txtScore4.Clear()
          txtScore5.Clear()
          lblAverage.Text = ""
    
        End Try
      End Sub
    Thanks if yoyu can help, thanks if you cant.
    Sdog
    Thursday, April 14, 2011 2:22 AM

Answers

  • No need to use Try/Catch for data validation. How about something like this:

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
      Dim boxes() = {txtScore1, txtScore2, txtScore3, txtScore4, txtScore5}
      Dim total As Double
      For Each tBox In boxes
        Dim num As Double
        If Not CheckNumber(tBox, num) Then
          MessageBox.Show("Invalid numeric input")
          Exit Sub
        End If
        total += num
      Next
      lblAverage.Text = (total / boxes.Length).ToString
    End Sub
    
    Private Function CheckNumber(tBox As TextBox, ByRef theNumber As Double) As Boolean
      If Double.TryParse(tBox.Text, theNumber) Then Return True
      tBox.Text = "Enter a number"
      Return False
    End Function
    
    

    Thursday, April 14, 2011 3:02 AM
  • if you want to validate the input as the text is typed, then you need to handle the OnTextChanged event, so that as each character is entered, you check the value. from the OnTextChaned event, you can call the CheckNumber(Textbox, Double) method.

    to create a TextChanged handler, just double click on a Textbox in the designer. it will create a method stub for you.

    then add a call so it looks like this (assuming "theNumber" is declared at the class level):

     

     Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
      If Not CheckNumber(TextBox1, theNumber) Then
       MessageBox.Show("Enter only Numbers")
       'clearing code
      End If
     End Sub
    

     

    as for clearing your textboxes (in case this has not yet been answered), just set their text equal to ""

     

    Textbox1.Text = ""
    

     

    otherwise your try/catch logic seems fine, though I agree it is not really right for this instance, since there are plenty of ways to address the problem before an exception occurs. are you having trouble with it?


    Thursday, April 14, 2011 4:29 AM
  •  

    Try this function, it should eliminate the problem without the user having to retype the values:

     

     Shared Function OnlyNumbers(ByVal Input As String)
      Input = Input.Replace(",", ".")
    
      Dim chrs As Char() = Input.ToCharArray
      Dim d() As Char = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ".", ","}
      Dim nul As Char = "0"
      Dim HasADot As Boolean = False
      Dim number As Double
      Dim NewString As String
    
      For i As Integer = 0 To chrs.GetUpperBound(0) Step 1
       If HasADot And chrs(i) = "." Then
        chrs(i) = ""
       End If
    
       If Not HasADot And chrs(i) = "." Then
        HasADot = True
    
       End If
    
       If chrs(i) = d(0) Or chrs(i) = d(1) Or chrs(i) = d(2) _
         Or chrs(i) = d(3) Or chrs(i) = d(4) Or chrs(i) = d(5) _
         Or chrs(i) = d(6) Or chrs(i) = d(7) Or chrs(i) = d(8) _
         Or chrs(i) = d(9) Or chrs(i) = d(10) Or chrs(i) = d(11) Then
        NewString &= chrs(i)
       End If
    
      Next
      If NewString <> String.Empty Then number = Convert.ToDouble(NewString)
      Return number
     End Function
    
    

    Usage :

     

    NumericValue = OnlyNumbers(YourDamagedNumberString)
    'It returns a double form a damaged number as string
    

     

     

     


    Friday, April 15, 2011 5:16 AM

All replies

  • No need to use Try/Catch for data validation. How about something like this:

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
      Dim boxes() = {txtScore1, txtScore2, txtScore3, txtScore4, txtScore5}
      Dim total As Double
      For Each tBox In boxes
        Dim num As Double
        If Not CheckNumber(tBox, num) Then
          MessageBox.Show("Invalid numeric input")
          Exit Sub
        End If
        total += num
      Next
      lblAverage.Text = (total / boxes.Length).ToString
    End Sub
    
    Private Function CheckNumber(tBox As TextBox, ByRef theNumber As Double) As Boolean
      If Double.TryParse(tBox.Text, theNumber) Then Return True
      tBox.Text = "Enter a number"
      Return False
    End Function
    
    

    Thursday, April 14, 2011 3:02 AM
  • That is great i will use that some time,...

    However i have to follow a format, that sure sounds quicker and tidier though. I may use that in my capstone project.

    I must add the explicit and strict options are on. I dont think that makes any difference to your answer though.

    Private Function CheckNumber(tBox As TextBox, ByRef theNumber As Double) As Boolean
      If Double.TryParse(tBox.Text, theNumber) Then Return True
      tBox.Text = "Enter a number"
      Return False
    End Function

    will this function work stand alone as the user types the input?

    I really do have a lot to learn ive been doing this for 4 weeks allready i feel swamped...

     


    Sdog
    Thursday, April 14, 2011 3:19 AM
  • if you want to validate the input as the text is typed, then you need to handle the OnTextChanged event, so that as each character is entered, you check the value. from the OnTextChaned event, you can call the CheckNumber(Textbox, Double) method.

    to create a TextChanged handler, just double click on a Textbox in the designer. it will create a method stub for you.

    then add a call so it looks like this (assuming "theNumber" is declared at the class level):

     

     Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
      If Not CheckNumber(TextBox1, theNumber) Then
       MessageBox.Show("Enter only Numbers")
       'clearing code
      End If
     End Sub
    

     

    as for clearing your textboxes (in case this has not yet been answered), just set their text equal to ""

     

    Textbox1.Text = ""
    

     

    otherwise your try/catch logic seems fine, though I agree it is not really right for this instance, since there are plenty of ways to address the problem before an exception occurs. are you having trouble with it?


    Thursday, April 14, 2011 4:29 AM
  • Both Doas and Blackwood shows you even the most easiest format, as in that hexadecimal, exponent way typed numbers not are handled as numbers. 

    This easy fits for all way you want,  is no way for VB or any other higher program language meant method.

    Those program languages are meant to make programs which can be used by end users which can be far away so they have to be fool proof..

     


    Success
    Cor
    Thursday, April 14, 2011 6:58 AM
  • No, the method works well. and i have added the code to clear all text boxes and labels. it would be good just to clear only the text box that causes the exception.

     


    Sdog
    Thursday, April 14, 2011 5:46 PM
  • well, the way i would handle that, is by separating out the code where you parse the text as double into a method, that way you can handle exceptions from each textbox separately, and blank them selectively.

     Private Function GetTextAsDouble(ByVal tb As TextBox) As Double
        Try
          Return CDbl(tb.Text)
        Catch ex As Exception
          tb.Text = ""
          Throw
        End Try
      End Function
    
      Public Sub GetAvgScore()
        Dim dblScore1 As Double
        Dim dblScore2 As Double
        Dim dblScore3 As Double
        Dim dblScore4 As Double
        Dim dblScore5 As Double
        Const dblSubtotal As Double = 5
        Dim dblAverage As Double
    
        Try
          dblScore1 = GetTextAsDouble(txtScore1)
          dblScore2 = GetTextAsDouble(txtScore2)
          dblScore3 = GetTextAsDouble(txtScore3)
          dblScore4 = GetTextAsDouble(txtScore4)
          dblScore5 = GetTextAsDouble(txtScore5)
    
          dblAverage = ((dblScore1 + dblScore2 + dblScore3 + dblScore4 + dblScore5) / dblSubtotal)
          lblAverage.Text = dblAverage.ToString
        Catch ex As Exception
          MessageBox.Show("numbers only please")
          lblAverage.Text = ""
        End Try
      End Sub
    

    so you pass the textbox itself into the GetTextAsDouble function. the function attempts to get the value as double, but if it can't it blanks out the textbox text. it then "Throws" the exception back to the caller. this is important, so that your math code does not just continue, despite the error. after hitting the line "throw" the catch block in GetAvgScore() will catch the thrown exception, skipping over the calculations, and prompting the user for new input. note however that if the user messes up in multiple textboxes, only the first one miss entered will be cleared.

    Friday, April 15, 2011 2:48 AM
  • ahahh i think, i am sure i do not understand your explanation as i am a hands on learner, my words would be.

    this tb.text will catch the non numeros trying to sneak in and by the but of their pants kick them boo.asking for a new number? you me and hamsters everywhere rejoice.

    or somthing along those lines. when i wake tommorow i will try that method on a new and more barbaric program. reducing dungeon master to a halfling cleric!!!

    ok just kidding, just played baldurs gate for a few.

    will try thanks

     


    Sdog
    Friday, April 15, 2011 3:05 AM
  • heh. never tried baldurs gate. I've always been more of a "Paper and Dice" kinda guy, myself.

    anyway, since this sounds like homework, give it a try and let us know what questions you have about it. exception handling is easy to do, but harder to do right. the easiest way to understand the flow of this code, is to set a breakpoint and step through the code in the debugger with F11 to watch how the flow moves for both valid and invalid inputs.


    Friday, April 15, 2011 4:13 AM
  •  

    Try this function, it should eliminate the problem without the user having to retype the values:

     

     Shared Function OnlyNumbers(ByVal Input As String)
      Input = Input.Replace(",", ".")
    
      Dim chrs As Char() = Input.ToCharArray
      Dim d() As Char = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ".", ","}
      Dim nul As Char = "0"
      Dim HasADot As Boolean = False
      Dim number As Double
      Dim NewString As String
    
      For i As Integer = 0 To chrs.GetUpperBound(0) Step 1
       If HasADot And chrs(i) = "." Then
        chrs(i) = ""
       End If
    
       If Not HasADot And chrs(i) = "." Then
        HasADot = True
    
       End If
    
       If chrs(i) = d(0) Or chrs(i) = d(1) Or chrs(i) = d(2) _
         Or chrs(i) = d(3) Or chrs(i) = d(4) Or chrs(i) = d(5) _
         Or chrs(i) = d(6) Or chrs(i) = d(7) Or chrs(i) = d(8) _
         Or chrs(i) = d(9) Or chrs(i) = d(10) Or chrs(i) = d(11) Then
        NewString &= chrs(i)
       End If
    
      Next
      If NewString <> String.Empty Then number = Convert.ToDouble(NewString)
      Return number
     End Function
    
    

    Usage :

     

    NumericValue = OnlyNumbers(YourDamagedNumberString)
    'It returns a double form a damaged number as string
    

     

     

     


    Friday, April 15, 2011 5:16 AM
  • thank you all. i have tried the methods below ermm i am sure i do them wrong i finished that anyway and got 98% grade thanks. BTW asking for advise is allowed as a learning tool so thanks. i am going to post a new thread same topic and code will be included. it is a working program same issue i have handled the negative numeric with if statements it is the non numerics that is bothering me. Thanks Again

    SDog.

     


    Sdog
    Tuesday, April 19, 2011 8:18 PM