Search code examples
vb.netmathtextboxreal-time

Adding multiple textboxes real time


When I run my code, I am able to successfully input values into other textboxes, but it does not sum all of the values into a textbox (txttotalcount) in real-time. It stays as a blank textbox.

I've tried using the txttotalcount_TextChanged. All other sources I've read uses the Button_Click, but I would like for the arithmetic to happen in real-time (no need to click a button).

I defined my textboxes to add +1 increment on button press:

Private Sub btnPMN_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPMN.Click
    'Add +1 to PMN Textbox (txtPMN)

    txtPMN.Text = (Val(txtPMN.Text) + 1).ToString()
End Sub

Private Sub BtnBand_Click(sender As Object, e As EventArgs) Handles btnBand.Click
    'Add +1 to Band Textbox (txtBand)

    txtBand.Text = (Val(txtBand.Text) + 1).ToString()
End Sub

Then I tried taking those textbox values and adding it into a final textbox (txttotalcount):

Private Sub Txttotalcount_TextChanged(sender As Object, e As EventArgs) Handles txttotalcount.TextChanged
    'Adds all text boxes 
    txttotalcount.text = txtPMN.Text + txtBand.Text


End Sub

I would like to sum all textboxes into a final textbox called txttotalcount.text in real-time (no button clicks)

When I run my code, the txttotalcount stays blank although there are values in the other textboxes.


Solution

  • or you can use these as alternative:

    Private Sub btnPMN_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPMN.Click
        txtIncrement(txtPMN, 1)
        Calculate()
    End Sub
    
    Private Sub BtnBand_Click(sender As Object, e As EventArgs) Handles BtnBand.Click
        txtIncrement(txtBand, 1)
        Calculate()
    End Sub
    
    Private Sub txtIncrement(ByRef myTextBox As TextBox, increment As Integer)
        If IsNumeric(myTextBox.Text) Then myTextBox.Text = (CLng(myTextBox.Text) + increment).ToString Else myTextBox.Text = 0
    End Sub
    
    Private Sub Calculate()
        txttotalcount.Text = "0"
        Dim myBand As Long = 0
        Dim myPMN As Long = 0
        If IsNumeric(txtBand.Text) Then myBand = CLng(txtBand.Text)
        If IsNumeric(txtPMN.Text) Then myPMN = CLng(txtPMN.Text)
        txttotalcount.Text = (myBand + myPMN).ToString("#,##0")
    End Sub