Solved

Total in textboxes

Posted on 2016-11-02
9
35 Views
Last Modified: 2016-11-04
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 .
0
Comment
Question by:RIAS
  • 6
  • 2
9 Comments
 
LVL 18

Expert Comment

by:Anil Golamari
ID: 41870442
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
 

Author Comment

by:RIAS
ID: 41870450
Thanks Anil ,

I am using vb.net .Can we have code in vb.net please?
0
 
LVL 32

Accepted Solution

by:
it_saige earned 500 total points
ID: 41870509
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
 

Author Closing Comment

by:RIAS
ID: 41870566
Thank you Sir!
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Author Comment

by:RIAS
ID: 41872038
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
 
LVL 32

Expert Comment

by:it_saige
ID: 41872070
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
 

Author Comment

by:RIAS
ID: 41872077
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
 

Author Comment

by:RIAS
ID: 41872118
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
 

Author Comment

by:RIAS
ID: 41874242
it worked perfectly with few tweaks! Thanks
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

This article describes relatively difficult and non-obvious issues that are likely to arise when creating COM class in Visual Studio and deploying it by professional MSI-authoring tools. It is assumed that the reader is already familiar with the cla…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

26 Experts available now in Live!

Get 1:1 Help Now