user12101961
user12101961

Reputation:

Calculate sum all lines in Textboxes

How to use that code for value with 3 Digit and 4 Digit and 5? (574, 3743, 31784, 478434) enter image description here

  Dim total As Single = 0.00
        For Each line As String In TextBox1.Text
            If IsNumeric(line) Then
                total += CSng(line)
            End If
        Next
        TextBox2.Text = total

That's code calculate sum only with 2 Digit, i want calculate Sum with 2-3-4-5-6 Digit.

Upvotes: 0

Views: 474

Answers (2)

dba
dba

Reputation: 1175

IMHO using a Textbox for a list of values might not be the best choice. Textboxes are meant for inputting one peace of data into each. But if you don't want to or can't use Listboxes, or something similar, you could put in the whole formula in the Textbox (12+124+...) including the operators and let the value be calculated by some extenal library such as NCalc. This way you could do some other calculations too.

Linebreak in a textbox as separator is not 100% safe, since a user could put in as many spaces as needed to reach overflow to the next line (assuming fixed/maximized width of the control).

And according to Devcon's answer, your loop only works in first place, because a string is actually an Array of characters, so a loop will take any single character and do the addition :) - breaks if there is a non-numeric one though.

Upvotes: 1

OctaCode
OctaCode

Reputation: 645

it should be

For Each line As String In TextBox1.Text.Split(vbLf)

instead of

For Each line As String In TextBox1.Text

btw even if you are using 1 2 or any num of digits, you should split by new line so you don't get any errors

if you want to know how you got 87, it's because you are ADDING: 1+2+1+2+4+2+0+0+4+7+4+7+8+4+5+7+1+4+2+1+2+7+8+4 = 87

Upvotes: 1

Related Questions