Results 1 to 11 of 11

Thread: Adding two textbox values together on Leave

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Apr 2003
    Location
    Three Rivers, MI
    Posts
    354

    Adding two textbox values together on Leave

    I am trying to keep the sum of two textboxes in another textbox. The problem that I have is that the two numbers can change often so I need it to update everytime a change is made to the amount in one of the textboxes. If I do a function like this I get an error after the first number is entered because there is no second number yet. What is the proper way to this so that if only one box is filled it will assume the other textbox has a zero value?
    VB Code:
    1. Private Sub txtMaterial_Leave(ByVal sender As Object, _
    2.         ByVal e As System.EventArgs) Handles txtMaterial.Leave
    3.  
    4.         txtTotal.Text = TotalAmount()
    5.  
    6.     End Sub
    7.  
    8.     Private Sub txtLabor_Leave(ByVal sender As Object, _
    9.         ByVal e As System.EventArgs) Handles txtLabor.Leave
    10.  
    11.         txtTotal.Text = TotalAmount()
    12.  
    13.     End Sub
    14.  
    15.     Function TotalAmount()
    16.         Dim sngLabor As Single = 0
    17.         Dim sngMaterial As Single = 0
    18.         sngLabor = txtLabor.Text
    19.         sngMaterial = txtMaterial.Text
    20.         Return sngMaterial + sngLabor
    21.     End Function

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Adding two textbox values together on Leave

    VB Code:
    1. Private Function GetTotalAmount() As Single
    2.         GetTotalAmount = 0S
    3.  
    4.         If Me.txtLabor.Text <> String.Empty AndAlso IsNumeric(Me.txtLabor.Text) Then
    5.             GetTotalAmount += Convert.ToSingle(Me.txtLabor.Text)
    6.         End If
    7.  
    8.         If Me.txtMaterial.Text <> String.Empty AndAlso IsNumeric(Me.txtMaterial.Text) Then
    9.             GetTotalAmount += Convert.ToSingle(Me.txtMaterial.Text)
    10.         End If
    11.     End Function
    There are several things to note here. Everthing is done explicitly, rather than letting the String from the TextBox be implicitly converted to a Single. This is not absolutely necessary, but good practice to help avoid difficult to find errors. Try going to the project properties and setting Option Explicit and Option Strict to On if they aren't already and see what changes you need to make. I also initialised the value as a single by putting the "S" after the "0". Also, this code checks to make sure that the TextBox contains a valid number before converting it to a Single. Finally, every VB.NET function has a local variable, of the same name and type, that can be assigned to in lieu of using a return statement. Note the use of GetTotalAmount as a variable.

    Edit:
    I think the first part of each If statement is redundant.
    Last edited by jmcilhinney; Jun 16th, 2005 at 10:58 PM.

  3. #3
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Adding two textbox values together on Leave

    For the "pure .NET" enthusiasts, you could use Double.TryParse instead of IsNumeric, although you have to pass a double as an argument to hold the parsed value if it succeeds:
    VB Code:
    1. Private Function GetTotalAmount() As Single
    2.         GetTotalAmount = 0S
    3.  
    4.         Dim textValue As Double
    5.  
    6.         If Double.TryParse(Me.txtLabor.Text, Globalization.NumberStyles.Number, Nothing, textValue) Then
    7.             GetTotalAmount += Convert.ToSingle(textValue)
    8.         End If
    9.  
    10.         If Double.TryParse(Me.txtMaterial.Text, Globalization.NumberStyles.Number, Nothing, textValue) Then
    11.             GetTotalAmount += Convert.ToSingle(textValue)
    12.         End If
    13.     End Function

  4. #4

    Thread Starter
    Hyperactive Member
    Join Date
    Apr 2003
    Location
    Three Rivers, MI
    Posts
    354

    Re: Adding two textbox values together on Leave

    jmcilhinney I am not sure I really understand that yet but it works. Thank you very much.

    I turned Option Strict on and Option Explicit was already on. I found 4 errors, which I think I can figure out two of them based on your last post. However these two are a little more confusing to me.
    VB Code:
    1. If dr.HasRows Then
    2.                 While dr.Read()
    3.                     txtJobName.Text = dr("Description")
    4.                 End While
    5.             Else
    Option Strict On disallows implicit conversions from 'System.Object' to 'String'. It highlights dr("Description")

    And this
    VB Code:
    1. Dim arrCharCount() As String = strCharCount.Split("-")
    Option Strict On disallows implicit conversions from 'String' to 'Char'. It highlights the "-"

  5. #5
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Adding two textbox values together on Leave

    The first error occurs because the Item property of the DataRow class, which you are invoking in that line, returns an Object. Your app doesn't know until run-time what actual type of object is contained in the column. You need to cast it as a String if you are assigning it to a String variable, which TextBox.Text is:
    VB Code:
    1. txtJobName.Text = CStr(dr("Description"))
    The second error occurs because the argument you are passing to Split is a String. If you want to pass the dash symbol as a character, do so like this:
    VB Code:
    1. Dim arrCharCount() As String = strCharCount.Split("-"c)
    You obviously don't have to have Option Strict set to On if you don't want. It can make coding a little more tedious, but it helps to enforce good practice, reduces errors and makes your code more efficient by reducing the load of late binding from implicit conversions.

  6. #6

    Thread Starter
    Hyperactive Member
    Join Date
    Apr 2003
    Location
    Three Rivers, MI
    Posts
    354

    Re: Adding two textbox values together on Leave

    I think I will leave it on for now. I want to eventually write some decent code and being forced to write it more correctly by the IDE will only help my understanding.

    While we are on this subject am I doing this part correctly?

    txtTotal.Text = CStr(GetTotalAmount())

    At first I thought I needed to use CSng because I needed to convert the string into a Single but that didn't work. Then I realized it was already converted to a Single in the Function so that was not needed. I tried it converting it to a string and it seems to work fine now.

    I am assuming that a textbox needs to have any data put into it converted to a string first before it can except it (when explicit/strict is on). If so that must mean in the past my "applications" were always doing the conversion at run time based on best guesses.

    Am I on the right track?

  7. #7
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Adding two textbox values together on Leave

    Quote Originally Posted by BukHix
    I think I will leave it on for now. I want to eventually write some decent code and being forced to write it more correctly by the IDE will only help my understanding.

    While we are on this subject am I doing this part correctly?

    txtTotal.Text = CStr(GetTotalAmount())

    At first I thought I needed to use CSng because I needed to convert the string into a Single but that didn't work. Then I realized it was already converted to a Single in the Function so that was not needed. I tried it converting it to a string and it seems to work fine now.

    I am assuming that a textbox needs to have any data put into it converted to a string first before it can except it (when explicit/strict is on). If so that must mean in the past my "applications" were always doing the conversion at run time based on best guesses.

    Am I on the right track?
    Yes you are on the right track. If you have a look at the Text property of the TextBox class, you will see that it is of type String. This means that whatever gets assigned to it must be a String. If Option Strict is On, then you must convert anything that is not a string yourself. If Option Strict is Off, then the ToString method, which every object has, is called implicitly to do the conversion. When you do an assignment by setting any variable or property to be equal to some value, you just need to check the type of the variable or property you are assigning to know whether you need to do a conversion or not. In the IDE, if you simply hover the mouse cursor over a variable or property it will tell you its type.

    Edit:
    Note that I used CStr in my previous example because I knew that the value was already a string. If you are converting something that you isn't a string or whose type you don't know, I would suggest calling its ToString method. Be aware that CStr(myObject) and myObject.ToString() do not always return the same string. I can't think of a specific case right now but I know I've seen situations where they do not match.
    Last edited by jmcilhinney; Jun 17th, 2005 at 07:33 PM.

  8. #8

    Thread Starter
    Hyperactive Member
    Join Date
    Apr 2003
    Location
    Three Rivers, MI
    Posts
    354

    Re: Adding two textbox values together on Leave

    I have one more function to make and I am stumped once again. In this case I am trying to figure out Gross Profit, which is basically the contract amount - total cost. I have tried this several ways but none of them seem to work. What am I doing wrong?
    VB Code:
    1. Private Function GetGrossProfit() As Single
    2.         GetGrossProfit = 0S
    3.         Dim sngContract As Single
    4.         Dim sngTotal As Single
    5.         If Me.txtContractAmt.Text <> String.Empty _
    6.             AndAlso IsNumeric(Me.txtContractAmt.Text) Then
    7.  
    8.             sngContract = Convert.ToSingle(Me.txtContractAmt.Text)
    9.  
    10.         End If
    11.         If Me.txtTotal.Text <> String.Empty _
    12.             AndAlso IsNumeric(Me.txtTotal) Then
    13.  
    14.             sngTotal = Convert.ToSingle(Me.txtTotal.Text)
    15.  
    16.         End If
    17.         GetGrossProfit = sngContract - sngTotal
    18.     End Function
    Thanks again. You have been a great help.

  9. #9
    Frenzied Member
    Join Date
    Nov 2003
    Posts
    1,489

    Re: Adding two textbox values together on Leave

    Just a small tip for you. you don't HAVE to have the IF statement to check for dr. While dr.Read will return true or false depending on whether or not it has rows. you could simplifiy your code just a tad.

  10. #10
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Adding two textbox values together on Leave

    You are passing the actual TextBox to IsNumeric in your second If statement, rather than its Text property, so it will always be False.

    A couple of other points. You may or may not be aware that, because it is a value type, a Single is initialised to zero when declared. That means that sngContract and sngTotal are each zero at the final calculation if the corresponding If statement is False. This may or may not yield the result that you want. Also, I pointed out the implicit local variable in the function because, in my example, I used it several times along the way so it saved me declaring an extra local variable. In your case, you declare the extra local variables anyway and only use the implicit variable once at the end. In that case, I would just use a return statement. I hope I'm not confusing you, but I would change your code to either of these:
    VB Code:
    1. Private Function GetGrossProfit() As Single
    2.         'This line is not actually needed because a Single is initialised to zero by default.
    3.         'It is good practice to include it to show that you want it to be zero by design rather than just by default.
    4.         GetGrossProfit = 0S
    5.  
    6.         If IsNumeric(Me.txtContract.Text) Then
    7.             'The implicit variable is used first here, where a return statement could not.
    8.             GetGrossProfit += Convert.ToSingle(Me.txtContract.Text)
    9.         End If
    10.  
    11.         If IsNumeric(Me.txtTotal.Text) Then
    12.             GetGrossProfit -= Convert.ToSingle(Me.txtTotal.Text)
    13.         End If
    14.     End Function
    VB Code:
    1. Private Function GetGrossProfit() As Single
    2.         Dim sngContract, sngTotal As Single
    3.  
    4.         If IsNumeric(Me.txtContract.Text) Then
    5.             sngContract = Convert.ToSingle(Me.txtContract.Text)
    6.         End If
    7.  
    8.         If IsNumeric(Me.txtTotal.Text) Then
    9.             sngTotal = Convert.ToSingle(Me.txtTotal.Text)
    10.         End If
    11.  
    12.         Return sngContract - sngTotal
    13.     End Function
    Notice that I've removed the "<> String.Empty" bits as well. I edited my original post earlier to point out that IsNumeric will account for that case so it is redundant.
    Last edited by jmcilhinney; Jun 18th, 2005 at 07:29 PM.

  11. #11

    Thread Starter
    Hyperactive Member
    Join Date
    Apr 2003
    Location
    Three Rivers, MI
    Posts
    354

    Re: Adding two textbox values together on Leave

    Don't worry I came into this confused. You have help me a lot. I'm hoping that I can use these example to accomplish the rest of the math functions in this application. I have three more to do. Anyway thanks again and I really do appreciate you taking the time to explain your examples to me.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width