Solved

Total in textboxes

Posted on 2016-11-02
9
72 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 33

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
Webinar: Aligning, Automating, Winning

Join Dan Russo, Senior Manager of Operations Intelligence, for an in-depth discussion on how Dealertrack, leading provider of integrated digital solutions for the automotive industry, transformed their DevOps processes to increase collaboration and move with greater velocity.

 

Author Closing Comment

by:RIAS
ID: 41870566
Thank you Sir!
0
 

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 33

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

Forrester Webinar: xMatters Delivers 261% ROI

Guest speaker Dean Davison, Forrester Principal Consultant, explains how a Fortune 500 communication company using xMatters found these results: Achieved a 261% ROI, Experienced $753,280 in net present value benefits over 3 years and Reduced MTTR by 91% for tier 1 incidents.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
VB.Net error: An exception occurred during a WebClient request 6 41
API v SOA 8 42
Name Space error VS2015 1 37
Code works but breaks when I add one section 4 29
In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

733 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