Newbie: tyring to use numbers in a textbox

Ok, I am kind of stuck on how to accomplish the following:

I am using 8 texboxes that will contain only numbers (ranging from -50 to 50, no decimals)

Textbox 1 will contain the sum of all of the other texboxes.

I can fill the other 7 textboxes with the numbers, but how do I add them together, and make it so that text box 1 will constantly add the sum of the other 7 text boxes (incase the values change later)

Thanks in advanced.




Answer this question

Newbie: tyring to use numbers in a textbox

  • Jonathon Howey

    Hi there,

    You could consider using the IsNumeric() function, which is contained in the Microsoft.VisualBasic namespace (so you need to add "Imports Microsoft.VisualBasic" to your code if you don't want to write out a fully qualified name).

    If you set your conditional to something like

    If Not String.IsNullOrEmpty(CType(Ctrl, TextBox).Text) And IsNumeric(CType(Ctrl, TextBox).Text) Then


    Then any text box that doesn't have something in it that is currently numeric will be ignored until the value in the text box is numeric. So, in the situation with the negative numbers, you won't get an error and the text box containing the "-" will be ignored until you complete typing in something like "-5".

    Hope that helps a bit, but sorry if it doesn't


  • Ayyanar

    Spotty,

    Thanks, that was exactly what I was looking for.  I only made minor changes to the code you supplied to fit into the form that I created.

    Function RecalcTotal() As Integer

    Dim Total As Integer = 0

    For Each Ctrl As Control In Me.Controls

    If TypeOf (Ctrl) Is TextBox And Ctrl.Name.StartsWith("AC") Then

    If Not String.IsNullOrEmpty(CType(Ctrl, TextBox).Text) Then

    Total += (CType(CType(Ctrl, TextBox).Text, Integer))

    End If

    End If

    Next

    Return Total

    End Function

    Private Sub textboxestextchanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ACArmorBonus.TextChanged, ACdeflectbonustb.TextChanged, ACdexmodtb1.TextChanged, ACmiscmodtb.TextChanged, ACnatarmortb.TextChanged, ACShieldBonus.TextChanged, ACSizeModtb1.TextChanged

    TotalAC.Text = 10 + RecalcTotal()

    End Sub

     

    It works beautifully.  The only problem is, if there is a negative value placed in one of the textboxes, it throws this error:

    InvalidCastException was Unhandled

    Conversion from string "-" to type 'Integer' is not valid.

    Did I do something wrong



  • deeban

    well, the nice thing is that most of the texboxes will be auto filled with text from other parts of the form. When the textoboxes are filled like this, it doesn't cause any errors, there is really only one textbox that gets filled by the user and that is the one I was worried about.

    I looked up validation in the help menu, it seems overtly complicated to add validation to a texbox when NateV's solution works. In the sample provided you have to create a class then inherit it into the form, etc.

    do you think that this would be worhtwhile to do this for one textbox, or should I just leave it as is



  • MWR

    Hi there,

    Each of your text boxes has a TextChanged event (I believe that if you double click a text box on your form it will open up the code editor where you can type in code to handle the TextChanged event).

    The TextChanged event is also in the list when you click on the desired text box control and in the "Properties" pane you click the lightning bolt icon. You can add an event handler by double clicking in the cell next to the entry for "TextChanged".

    Now, if you want TextBox1 to update dynamically when you change the values in any of your other text boxes (TextBox2 through to TextBox7) then you will need to add code to the event handler for the TextChanged event for each text box except TextBox1.

    The code in the event handler will all the same in all cases, here's an example of one:

    Private Sub TextBox2_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox2.TextChanged
        Try
            TextBox1.Text = recalcTextBoxTotals.ToString()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Notice that a function, recalcTextBoxTotals(), is called. This is one I made and it goes a little like this:

    Private Function recalcTextBoxTotals() As Integer
        Dim newTextBoxValue As Integer = 0

        If Not String.IsNullOrEmpty(TextBox2.Text) Then
            newTextBoxValue += Integer.Parse(TextBox2.Text).ToString()
        End If

        If Not String.IsNullOrEmpty(TextBox3.Text) Then
            newTextBoxValue += Integer.Parse(TextBox3.Text).ToString()
        End If

        Return newTextBoxValue
    End Function

    For the sake of brevity, I have only included two "If" statements....You will need to add the rest for each of the other text boxes. Each "If" statement will be the same execpt that the names of the text boxes will change.

    My way's not perfect and I'm sure the gurus around here can tell you a better way, but it's something to get you started.

    Hope that helps a bit, but sorry if it doesn't.


  • cystw

    Public Class Form1
    Function RecalcTotal() As Integer
    Dim total As Integer = 0

    For Each Ctrl As Control In Me.Controls
    If TypeOf (Ctrl) Is TextBox And Ctrl.Name.StartsWith("TextBox") Then
    If Not String.IsNullOrEmpty(CType(Ctrl, TextBox).Text) And IsNumeric(CType(Ctrl, TextBox).Text) Then
    total += CType(CType(Ctrl, TextBox).Text, Integer)
    End If
    End If
    Next
    Return total
    End Function

    Private Sub TextBoxesTextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged, TextBox2.TextChanged, TextBox3.TextChanged, TextBox4.TextChanged, TextBox5.TextChanged, TextBox6.TextChanged, TextBox7.TextChanged
    TxtTotal.Text = RecalcTotal()
    End Sub

    Private Sub TextBoxNumericOnly(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress, TextBox2.KeyPress, TextBox3.KeyPress, TextBox4.KeyPress, TextBox5.KeyPress, TextBox6.KeyPress, TextBox7.KeyPress
    If Char.IsControl(e.KeyChar) Then
    e.Handled = False
    ElseIf Char.IsNumber(e.KeyChar) Or e.KeyChar = "-" Then
    e.Handled = False
    Else
    e.Handled = True
    End If
    End Sub

    Private Sub TextboxOutOfRange(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged, TextBox2.TextChanged, TextBox3.TextChanged, TextBox4.TextChanged, TextBox5.TextChanged, TextBox6.TextChanged, TextBox7.TextChanged
    If IsNumeric(CType(sender, TextBox).Text) Then
    If CInt(CType(sender, TextBox).Text) < -50 Or CInt(CType(sender, TextBox).Text) > 50 Then
    CType(sender, TextBox).ForeColor = Color.Red
    Else
    CType(sender, TextBox).ForeColor = Color.Black
    End If
    End If
    End Sub

    End Class


  • Mike James

    Just to get the program to run, I added a try to the code:

    Try

    For Each Ctrl As Control In Me.Controls

    If TypeOf (Ctrl) Is TextBox And Ctrl.Name.StartsWith("AC") Then

    If Not String.IsNullOrEmpty(CType(Ctrl, TextBox).Text) Then

    Total += (CType(CType(Ctrl, TextBox).Text, Integer))

    End If

    End If

    Next

    Return Total

    catch ex as exception

    messagebox.show("Make sure to enter a value after -")

    end try

    This allows me to run the program. Luckily, for at least 90% of the time, there won't be any negative values in these texboxes. I would still like to see if there is anything to prevent this error from happening of course.



  • Mike Mason 2

    A similar general idea but this form will have 7 textboxes called TextBox1, .... Textbox7 as well as one Textbox called TxtTotal. The event handler on the textchnaged is hooked up for all the textboxes to run the recalc routine which will calculate the total of the textboxes called 1-7.

    This approach means to get it to add say 20 textboxes instead of 7 all you need to do is add Textboxes to the form and add the events to TextBoxesTextChanged method

    Public Class Form1

    Function RecalcTotal() As Integer
    Dim total As Integer = 0

    For Each Ctrl As Control In Me.Controls
    If TypeOf (Ctrl) Is TextBox And Ctrl.Name.StartsWith("TextBox") Then
    If Not String.IsNullOrEmpty(CType(Ctrl, TextBox).Text) Then
    total += CType(CType(Ctrl, TextBox).Text, Integer)
    End If
    End If
    Next
    Return total
    End Function

    Private Sub TextBoxesTextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged, TextBox2.TextChanged, TextBox3.TextChanged, TextBox4.TextChanged, TextBox5.TextChanged, TextBox6.TextChanged, TextBox7.TextChanged
    TxtTotal.Text = RecalcTotal()
    End Sub

    End Class


  • filament

    If CInt(CType(sender, TextBox).Text) < -50 Or CInt(CType(sender, TextBox).Text) > 50 Then

    This code causes the following error while trying to enter a negative value:

    InvalidCastException was Unhandled

    Conversion from string "-" to type 'Integer' is not valid.



  • zuomin

    I'd definately put some rudimentary stuff in there.

    The following will allow numbers and - sign only in the textbox and the textchanged event will highlight the textbox to red if its out of range. This coupled with the isnumeric will probably work quite nicely. So it prevents entering non numeric characters (except for - sign) into the textbox.

    And if the textbox is out of range the user is highlighted to this fact by the textbox turning red.

    Private Sub TextBoxNumericOnly(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
    If Char.IsControl(e.KeyChar) Then
    e.Handled = False
    ElseIf Char.IsNumber(e.KeyChar) Or e.KeyChar = "-" Then
    e.Handled = False
    Else
    e.Handled = True
    End If
    End Sub

    Private Sub TextboxOutOfRange(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
    If CInt(CType(sender, TextBox).Text) < -50 Or CInt(CType(sender, TextBox).Text) > 50 Then
    Me.TextBox1.ForeColor = Color.Red
    Else
    Me.TextBox1.ForeColor = Color.Black
    End If
    End Sub


  • Michael Brisset - MSFT

    Really - you should consider validation on the textboxes up front to ensure that they are valid rather than letting them type in garbage and then try and processing it.

    I'd consider some validation on the the textboxes prior to recalculation, to ensure that invalid values are highlighted and making the textboxes numeric only by only allowing numbers, - and control characters.


  • dmelfi

    Thanks Nate for that last peice of code, now it is working perfectly. And thanks to everyone for all of the help.

  • Newbie: tyring to use numbers in a textbox