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:
Private Sub txtMaterial_Leave(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles txtMaterial.Leave
txtTotal.Text = TotalAmount()
End Sub
Private Sub txtLabor_Leave(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles txtLabor.Leave
txtTotal.Text = TotalAmount()
End Sub
Function TotalAmount()
Dim sngLabor As Single = 0
Dim sngMaterial As Single = 0
sngLabor = txtLabor.Text
sngMaterial = txtMaterial.Text
Return sngMaterial + sngLabor
End Function
Re: Adding two textbox values together on Leave
VB Code:
Private Function GetTotalAmount() As Single
GetTotalAmount = 0S
If Me.txtLabor.Text <> String.Empty AndAlso IsNumeric(Me.txtLabor.Text) Then
GetTotalAmount += Convert.ToSingle(Me.txtLabor.Text)
End If
If Me.txtMaterial.Text <> String.Empty AndAlso IsNumeric(Me.txtMaterial.Text) Then
GetTotalAmount += Convert.ToSingle(Me.txtMaterial.Text)
End If
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.
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:
Private Function GetTotalAmount() As Single
GetTotalAmount = 0S
Dim textValue As Double
If Double.TryParse(Me.txtLabor.Text, Globalization.NumberStyles.Number, Nothing, textValue) Then
GetTotalAmount += Convert.ToSingle(textValue)
End If
If Double.TryParse(Me.txtMaterial.Text, Globalization.NumberStyles.Number, Nothing, textValue) Then
GetTotalAmount += Convert.ToSingle(textValue)
End If
End Function
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:
If dr.HasRows Then
While dr.Read()
txtJobName.Text = dr("Description")
End While
Else
Option Strict On disallows implicit conversions from 'System.Object' to 'String'. It highlights dr("Description")
And this
VB Code:
Dim arrCharCount() As String = strCharCount.Split("-")
Option Strict On disallows implicit conversions from 'String' to 'Char'. It highlights the "-"
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:
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:
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.
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?
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.
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:
Private Function GetGrossProfit() As Single
GetGrossProfit = 0S
Dim sngContract As Single
Dim sngTotal As Single
If Me.txtContractAmt.Text <> String.Empty _
AndAlso IsNumeric(Me.txtContractAmt.Text) Then
sngContract = Convert.ToSingle(Me.txtContractAmt.Text)
End If
If Me.txtTotal.Text <> String.Empty _
AndAlso IsNumeric(Me.txtTotal) Then
sngTotal = Convert.ToSingle(Me.txtTotal.Text)
End If
GetGrossProfit = sngContract - sngTotal
End Function
Thanks again. You have been a great help.
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.
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:
Private Function GetGrossProfit() As Single
'This line is not actually needed because a Single is initialised to zero by default.
'It is good practice to include it to show that you want it to be zero by design rather than just by default.
GetGrossProfit = 0S
If IsNumeric(Me.txtContract.Text) Then
'The implicit variable is used first here, where a return statement could not.
GetGrossProfit += Convert.ToSingle(Me.txtContract.Text)
End If
If IsNumeric(Me.txtTotal.Text) Then
GetGrossProfit -= Convert.ToSingle(Me.txtTotal.Text)
End If
End Function
VB Code:
Private Function GetGrossProfit() As Single
Dim sngContract, sngTotal As Single
If IsNumeric(Me.txtContract.Text) Then
sngContract = Convert.ToSingle(Me.txtContract.Text)
End If
If IsNumeric(Me.txtTotal.Text) Then
sngTotal = Convert.ToSingle(Me.txtTotal.Text)
End If
Return sngContract - sngTotal
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.
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.