Total in textboxes

Hello,
I am using vb.net 2015 desktop application.

I have 6 textboxes in which one will be occupied with an number .This textbox will be treated as a total  amount.
The requirement is if the user adds any amount of value in the rest of the 5 textboxes  the amount should get deducted from the 'total  amount.' textbox.

total  amount textbox can be any one the textboxes  present on the form.

Any suggestions on how can i achieve it .
RIASAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
it_saigeConnect With a Mentor DeveloperCommented:
Use the validating and validated events to control your logic; e.g. -

Form1.vb -
Public Class Form1
	Private _total As TextBox = Nothing

	Private Sub OnLoad(sender As Object, e As EventArgs) Handles MyBase.Load

	End Sub

	Private Sub OnClick(sender As Object, e As EventArgs) Handles Button1.Click
		If TypeOf sender Is Button Then
			Dim btn = DirectCast(sender, Button)
			If btn.Equals(Button1) Then
				For Each [control] As Control In btn.Parent.Controls
					If TypeOf [control] Is TextBox Then
						CType([control], TextBox).ReadOnly = False
						CType([control], TextBox).ResetText()
					End If
				Next
				_total = Nothing
			End If
		End If
	End Sub

	Private Sub OnValidating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles TextBox6.Validating, TextBox5.Validating, TextBox4.Validating, TextBox3.Validating, TextBox2.Validating, TextBox1.Validating
		If TypeOf sender Is TextBox Then
			Dim tb = DirectCast(sender, TextBox)
			Dim valid As Boolean = True
			For Each c As Char In tb.Text
				If Char.IsLetter(c) Then
					valid = False
					Exit For
				End If
			Next

			e.Cancel = Not valid
			If e.Cancel Then
				MessageBox.Show("Invalid character sequence, must be a number")
			Else
				If _total Is Nothing AndAlso Not String.IsNullOrWhiteSpace(tb.Text) Then
					_total = tb
					tb.ReadOnly = True
				End If
			End If
		End If
	End Sub

	Private Sub OnValidated(sender As Object, e As EventArgs) Handles TextBox6.Validated, TextBox5.Validated, TextBox4.Validated, TextBox3.Validated, TextBox2.Validated, TextBox1.Validated
		If TypeOf sender Is TextBox Then
			Dim tb = DirectCast(sender, TextBox)
			If _total IsNot Nothing AndAlso Not _total.Equals(tb) Then
				If Not String.IsNullOrWhiteSpace(tb.Text) Then
					_total.Text = CDbl(_total.Text) - CDbl(tb.Text)
				End If
			End If
		End If
	End Sub
End Class

Open in new window

Form1.Designer.vb -
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form1
    Inherits System.Windows.Forms.Form

    'Form overrides dispose to clean up the component list.
    <System.Diagnostics.DebuggerNonUserCode()> _
    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        Try
            If disposing AndAlso components IsNot Nothing Then
                components.Dispose()
            End If
        Finally
            MyBase.Dispose(disposing)
        End Try
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()
		Me.Button1 = New System.Windows.Forms.Button()
		Me.TextBox1 = New System.Windows.Forms.TextBox()
		Me.TextBox2 = New System.Windows.Forms.TextBox()
		Me.TextBox3 = New System.Windows.Forms.TextBox()
		Me.TextBox4 = New System.Windows.Forms.TextBox()
		Me.TextBox5 = New System.Windows.Forms.TextBox()
		Me.TextBox6 = New System.Windows.Forms.TextBox()
		Me.SuspendLayout()
		'
		'Button1
		'
		Me.Button1.Location = New System.Drawing.Point(197, 91)
		Me.Button1.Name = "Button1"
		Me.Button1.Size = New System.Drawing.Size(75, 23)
		Me.Button1.TabIndex = 0
		Me.Button1.Text = "Reset"
		Me.Button1.UseVisualStyleBackColor = True
		'
		'TextBox1
		'
		Me.TextBox1.Location = New System.Drawing.Point(13, 13)
		Me.TextBox1.Name = "TextBox1"
		Me.TextBox1.Size = New System.Drawing.Size(100, 20)
		Me.TextBox1.TabIndex = 1
		'
		'TextBox2
		'
		Me.TextBox2.Location = New System.Drawing.Point(172, 13)
		Me.TextBox2.Name = "TextBox2"
		Me.TextBox2.Size = New System.Drawing.Size(100, 20)
		Me.TextBox2.TabIndex = 2
		'
		'TextBox3
		'
		Me.TextBox3.Location = New System.Drawing.Point(13, 39)
		Me.TextBox3.Name = "TextBox3"
		Me.TextBox3.Size = New System.Drawing.Size(100, 20)
		Me.TextBox3.TabIndex = 3
		'
		'TextBox4
		'
		Me.TextBox4.Location = New System.Drawing.Point(172, 39)
		Me.TextBox4.Name = "TextBox4"
		Me.TextBox4.Size = New System.Drawing.Size(100, 20)
		Me.TextBox4.TabIndex = 4
		'
		'TextBox5
		'
		Me.TextBox5.Location = New System.Drawing.Point(13, 65)
		Me.TextBox5.Name = "TextBox5"
		Me.TextBox5.Size = New System.Drawing.Size(100, 20)
		Me.TextBox5.TabIndex = 5
		'
		'TextBox6
		'
		Me.TextBox6.Location = New System.Drawing.Point(172, 65)
		Me.TextBox6.Name = "TextBox6"
		Me.TextBox6.Size = New System.Drawing.Size(100, 20)
		Me.TextBox6.TabIndex = 6
		'
		'Form1
		'
		Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
		Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
		Me.ClientSize = New System.Drawing.Size(284, 123)
		Me.Controls.Add(Me.TextBox6)
		Me.Controls.Add(Me.TextBox5)
		Me.Controls.Add(Me.TextBox4)
		Me.Controls.Add(Me.TextBox3)
		Me.Controls.Add(Me.TextBox2)
		Me.Controls.Add(Me.TextBox1)
		Me.Controls.Add(Me.Button1)
		Me.Name = "Form1"
		Me.Text = "Form1"
		Me.ResumeLayout(False)
		Me.PerformLayout()

	End Sub
	Friend WithEvents Button1 As System.Windows.Forms.Button
	Friend WithEvents TextBox1 As System.Windows.Forms.TextBox
	Friend WithEvents TextBox2 As System.Windows.Forms.TextBox
	Friend WithEvents TextBox3 As System.Windows.Forms.TextBox
	Friend WithEvents TextBox4 As System.Windows.Forms.TextBox
	Friend WithEvents TextBox5 As System.Windows.Forms.TextBox
	Friend WithEvents TextBox6 As System.Windows.Forms.TextBox

End Class

Open in new window


Which produces the following output -

Initial load -Capture.JPGEntering a valid numeric sequence into one of the textboxes -Capture.JPGEntering a valid numeric sequence into another textbox -Capture.JPG
-saige-
0
 
Anil GolamariCommented:
Below is sample code that works for me.  

<form id="form1" runat="server">

 <script type="text/javascript">
        function sum() {
            var txtFirstNumberValue = document.getElementById('TextBox1').value;
            var txtSecondNumberValue = document.getElementById('TextBox2').value;
            var txtThridNumberValue = document.getElementById('TextBox3').value;
            var txtFourthNumberValue = document.getElementById('TextBox4').value;
            var txtFifthNumberValue = document.getElementById('TextBox5').value;
 
            if (txtFirstNumberValue == "")
                txtFirstNumberValue = 0;
 
            if (txtSecondNumberValue == "")
                txtSecondNumberValue = 0;
 
            if (txtThridNumberValue == "")
                txtThridNumberValue = 0;
 
            if (txtFourthNumberValue == "")
                txtFourthNumberValue = 0;
            if (txtFifthNumberValue == "")
                txtFifthNumberValue = 0;
 
            var result = parseInt(txtFirstNumberValue) + parseInt(txtSecondNumberValue) + parseInt(txtThridNumberValue) + parseInt(txtFourthNumberValue) + parseInt(txtFifthNumberValue);
            if (!isNaN(result)) {
                document.getElementById('TextBox6').value = result;
            }
        }
</script>


<div>

    <asp:TextBox ID="TextBox1" runat="server" onkeyup="sum();"></asp:TextBox>
    <br />
    <asp:TextBox ID="TextBox2" runat="server" onkeyup="sum();"></asp:TextBox>
    <br />
    <asp:TextBox ID="TextBox3" runat="server" onkeyup="sum();"></asp:TextBox>
    <br />
    <asp:TextBox ID="TextBox4" runat="server" onkeyup="sum();"></asp:TextBox>
    <br />
    <asp:TextBox ID="TextBox5" runat="server" onkeyup="sum();"></asp:TextBox>
    <br />
    <asp:TextBox ID="TextBox6" runat="server"></asp:TextBox>
    <br />

</div>
</form>

Open in new window

1
 
RIASAuthor Commented:
Thanks Anil ,

I am using vb.net .Can we have code in vb.net please?
0
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
RIASAuthor Commented:
Thank you Sir!
0
 
RIASAuthor Commented:
Hello Saige Sir,
It works great, but if I keep chaging my numbers in other textbox ,it goes in negative. Is there any way the total textbox should stop at 0 and respond to the changes done in the amount in the other textboxes?
0
 
it_saigeDeveloperCommented:
Either check the calculation result before setting the textbox text; e.g. -
Private Sub OnValidated(sender As Object, e As EventArgs) Handles TextBox6.Validated, TextBox5.Validated, TextBox4.Validated, TextBox3.Validated, TextBox2.Validated, TextBox1.Validated
	If TypeOf sender Is TextBox Then
		Dim tb = DirectCast(sender, TextBox)
		If _total IsNot Nothing AndAlso Not _total.Equals(tb) Then
			If Not String.IsNullOrWhiteSpace(tb.Text) Then
				Dim temp = CDbl(_total.Text) - CDbl(tb.Text)
				_total.Text = If(temp < 0, 0, temp)
			End If
		End If
	End If
End Sub

Open in new window

Or check the textbox text to see if it is less than zero after setting; e.g. -
Private Sub OnValidated(sender As Object, e As EventArgs) Handles TextBox6.Validated, TextBox5.Validated, TextBox4.Validated, TextBox3.Validated, TextBox2.Validated, TextBox1.Validated
	If TypeOf sender Is TextBox Then
		Dim tb = DirectCast(sender, TextBox)
		If _total IsNot Nothing AndAlso Not _total.Equals(tb) Then
			If Not String.IsNullOrWhiteSpace(tb.Text) Then
				_total.Text = CDbl(_total.Text) - CDbl(tb.Text)
				If CDbl(_total.Text) < 0 Then _total.Text = 0
			End If
		End If
	End If
End Sub

Open in new window


As for the second part of your follow-up question, I don't understand what you mean by "respond to the changes done in the amount in the other textboxes".

-saige-
1
 
RIASAuthor Commented:
Thanks Sir,

Sorry for the confusion

 "respond to the changes done in the amount in the other textboxes".


Will try to work on your solution.

Cheers!
0
 
RIASAuthor Commented:
Sir,

if I add value to the textbox ,it gets deducted from the total but, if I remove the value from textbox it does not get added back to to the total.
example:

1. total textbox    textbox1

    1000                      

2. total textbox    textbox1

    900                        100
3. total textbox    textbox1

    900                                                -------expected result is it should go back to 1000 but does not

Any suggestions Sir?

Cheers
0
 
RIASAuthor Commented:
it worked perfectly with few tweaks! Thanks
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.