Click here to Skip to main content
15,891,864 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
For example in textbox i have written 1020,when i will click on Explode button, it will show 3 in textbox, because 1+0+2+0=3.

What I have tried:

I have tired like this`
int total = 0;
total = int.Parse(button1.Text) + int.Parse(button2.Text) + int.Parse(button3.Text) + int.Parse(button4.Text) + int.Parse(button5.Text) + int.Parse(button6.Text) + int.Parse(button7.Text) + int.Parse(button8.Text) + int.Parse(button9.Text) + int.Parse(button11.Text);
textbox.Text = total.ToString();


But in this case when i click on Explode button it always show 45` because 1+2+3+4+5+6+7+8+9=45.
How can i write this code, in order it show me sum of my input numbers?
Posted
Updated 22-Feb-18 10:46am

Try this:
int total = 0;

foreach (char ch in this.textBox1.Text)
{
    total += int.Parse(ch.ToString());
}

this.textBox1.Text = total.ToString();
 
Share this answer
 
Comments
Suren97 22-Feb-18 13:28pm    
Thank you soo much :)
Maciej Los 22-Feb-18 13:37pm    
5ed!
phil.o 22-Feb-18 13:52pm    
My 5 too.
RickZeeland 22-Feb-18 13:54pm    
Muchas gracias !
Alternatively to solution #1 by RickZeeland[^], i'd provide Linq solution:

C#
string mytext = "1020";
int sumOfChars = mytext.Sum(x=>Convert.ToInt32(x.ToString())); //3 
 
Share this answer
 
Comments
phil.o 22-Feb-18 13:53pm    
5 :)
Maciej Los 22-Feb-18 13:54pm    
Thank you, Phil.
RickZeeland 22-Feb-18 13:57pm    
Elegant, 5d !
Maciej Los 22-Feb-18 13:58pm    
Thank you, Rick.
Have more:
int num = "1020".Sum(n => n & 15);

int sum = (int)"1020".Sum(n => Char.GetNumericValue(n));
Note: 'GetNumericValue returns a double, and I find that strange.
 
Share this answer
 
v2
Comments
Richard Deeming 23-Feb-18 9:59am    
+5. Much more efficient than converting each char to a string and then parsing it back to an int! :)

Char.GetNumericValue[^] returns a double because some characters represent fractions. For example:

* \u00BC = ¼ = 0.25
* \u00BD = ½ = 0.5
* \u00BE = ¾ = 0.75
BillWoodruff 23-Feb-18 12:11pm    
Thanks, Richard, I thought it might have something to do with Unicode, but, never thought of fractions :)
If you want to enter your data into a single textbox, let's start there.
Instead of looking at the value in each of 11 text boxes like you currently have, create a loop to look at each position in the data entered into a single text box.
Then, add the value of each position to your total.

Given this, you should be able to write the code.
If after writing the code to use a loop, you still have a question, post your modified code.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900