Adding the values of 2 textboxes to display result

2019-08-30 13:22发布

问题:

On my form I have 2 textboxes called 'txtsurcharges.text' and 'txttotal.text'

txttotal retrieves a value from mysql table, but what I want to happen is that this value becomes added to when I type in a value into txtsurcharges and display the result in txttotal.

Here is my code for txtsurcharges:

txtsurcharges.Text = String.Format("£{0}", txtsurcharges.Text)

Here is my code for txttotal:

Private Sub cbxPaymentID_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbxPaymentID.SelectedIndexChanged
        Dim dss As New DataSet
        If (cbxPaymentID.SelectedIndex <> -1) Then
            Dim daa As New MySqlDataAdapter("SELECT * from payment_details WHERE PaymentID=@PID", _
            objconnection)
            daa.SelectCommand.Parameters.AddWithValue("@PID", Convert.ToInt32(cbxPaymentID.SelectedValue))
            daa.Fill(dss)
            txttotal.Text = dss.Tables(0).Rows(0)("ServicePayment").ToString()

        End If
    End Sub

Here is my code for the addition of the 2 values, which doesn't work:

Private Sub txtsurcharges_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtsurcharges.TextChanged
        Dim c As Integer
        c = Val(txtsurcharges.Text) + Val(txttotal.Text)
        c = txttotal.Text
    End Sub

回答1:

Try this (UPDATED TO SHOW ASPX and VB code with a couple of static values for test)

aspx code

<asp:TextBox ID="txtsurcharges" runat="server" Text="£5" AutoPostBack="true"></asp:TextBox>
    <asp:TextBox ID="txttotal" runat="server" Text="£5"></asp:TextBox>

vb code

Private Sub txtsurcharges_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtsurcharges.TextChanged 
    Dim c As Integer 
    c = CInt(txtsurcharges.Text) + CInt(txttotal.Text) 
    txttotal.Text = c
End Sub

As you can see your were setting c to = the sum of surcharge and total and then you were resetting c back to total.

If I now change txtsurcharges to 10 then txttotal will change to 15.

You will of course need to make sure that only numerics can be typed into txtsurcharges.