Abdelmouttalib Abdelmouttalib - 5 months ago 11
Vb.net Question

How to simplify this if-else structure?

I'm looking for an easy and concise way to do this :

Example:

if textbox5.text = "1234" then textbox6.text= "10" (1+2+3+4)

If TextBox5.TextLength = 1 Then
TextBox6.Text = TextBox5.Text.Substring(0, 1)

ElseIf TextBox5.TextLength = 2 Then
TextBox6.Text = Val(TextBox5.Text.Substring(0, 1)) + Val(TextBox5.Text.Substring(1, 1))

ElseIf TextBox5.TextLength = 3 Then
TextBox6.Text = Val(TextBox5.Text.Substring(0, 1)) + Val(TextBox5.Text.Substring(1, 1)) + Val(TextBox5.Text.Substring(2, 1))

ElseIf TextBox5.TextLength = 4 Then
TextBox6.Text = Val(TextBox5.Text.Substring(0, 1)) + Val(TextBox5.Text.Substring(1, 1)) + Val(TextBox5.Text.Substring(2, 1)) +
Val(TextBox5.Text.Substring(3, 1))

ElseIf TextBox5.TextLength = 5 Then
TextBox6.Text = Val(TextBox5.Text.Substring(0, 1)) + Val(TextBox5.Text.Substring(1, 1)) + Val(TextBox5.Text.Substring(2, 1)) +
Val(TextBox5.Text.Substring(3, 1)) + Val(TextBox5.Text.Substring(4, 1))

ElseIf TextBox5.TextLength = 6 Then
TextBox6.Text = Val(TextBox5.Text.Substring(0, 1)) + Val(TextBox5.Text.Substring(1, 1)) + Val(TextBox5.Text.Substring(2, 1)) +
Val(TextBox5.Text.Substring(3, 1)) + Val(TextBox5.Text.Substring(4, 1)) + Val(TextBox5.Text.Substring(5, 1))

Answer

What you want to do is grab each character in the string, and convert it to a number and add it up, without the specific if/elses for different string lengths.

Dim i as integer
For Each c As Char in TextBox5.Text
    i= i + Integer.Parse(c)
Next
TextBox6.Text = i

I'm used to C#, so the syntax may not be exact, but this is generally what you are looking for.