Results 1 to 2 of 2

Thread: adding text box values

  1. #1

    Thread Starter
    Fanatic Member
    Join Date
    Sep 2002
    Posts
    779

    adding text box values

    i am writing a golf score program and i have 18 text boxes. i also have a text box that will calculate the total of all of the 18 other text boxes. what would be the best way to add these text boxes? i have already written code to only except numbers 1 thru 8 for each text box.

    i started with some code like this:
    Code:
    TextBoxTotal.Text = CInt(TextBoxHole1.Text) + CInt(TextBoxHole2.Text) + CInt(TextBoxHole3.Text)
    but if there is no value in one of the text boxes i get an error:
    Conversion from string "" to type 'Integer' is not valid.

    so i am guessing i need to check for empty strings and then ignore them

    any suggestions?

  2. #2
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,421

    Re: adding text box values

    here's my solution. it works with empty text + invalid entries:

    vb Code:
    1. Public Class Form1
    2.  
    3.     Dim textboxes() As TextBox
    4.  
    5.     Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    6.         textboxes = Me.Controls.OfType(Of TextBox).Where(Function(tb) tb.Name.StartsWith("TextBoxHole")).ToArray
    7.         For Each tb As TextBox In textboxes
    8.             AddHandler tb.TextChanged, AddressOf tb_TextChanged
    9.         Next
    10.     End Sub
    11.  
    12.     Private Sub tb_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
    13.         Dim sum As Decimal = 0D
    14.         For Each tb As TextBox In textboxes
    15.             Dim value As Decimal = 0D
    16.             Decimal.TryParse(tb.Text, value)
    17.             sum += value
    18.         Next
    19.         TextBoxTotal.Text = sum.ToString
    20.     End Sub
    21.  
    22. End Class

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width