anon
anon

Reputation:

richTextBox sum of all lines in c#

I'm learning to code and to get started I am creating small projects. I want to get the sum of all the lines in a richTextBox. All the lines in the richTextBox are numbers.

For example: - 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - 10

The result must be: 1+2+3+4+5+6+7+8+9+10 = 55. I want to display the result in a messagebox: "The sum is 55".

Upvotes: 0

Views: 880

Answers (2)

Nicolas Dias
Nicolas Dias

Reputation: 659

To do this it is necessary to divide the contents of the control RichTextBox in rows, performing the conversion for each line of type int and then performing the sum of all the numbers. Below is the implementation of the Sum method, responsible for adding and return the result:

    private int Sum()
    {
        //myrichtextbox is your rich control
        string myText = myrichtextbox.Text;
        var separators = new string[] { "\n" };
        var myNumbers = myText.Split(separators, StringSplitOptions.RemoveEmptyEntries);

        int sum = 0;

        foreach (var num in myNumbers)
        {
            int convertedNumber;
            if (Int32.TryParse(num, out convertedNumber))
                sum += convertedNumber;
        }

        return sum;
    }

End to display the result in a MessageBox use the following statement:

MessageBox.Show(String.Format("The sum result is: {0}.",Sum()));

Detail: I'm assuming you're using Windows Forms Application!

Upvotes: 0

msmolcic
msmolcic

Reputation: 6557

Try with this:

MessageBox.Show(string.Format("Sum of your numbers is {0}",
    richTextBox1.Text.Split('\n').Select(number => Convert.ToInt32(number)).Sum()));

Split text on new line character, convert everything from string array to numbers, get sum and display it in MessageBox.

Step by step solution:

string[] stringArray = richTextBox1.Text.Split('\n');

int sum = 0;
foreach (string element in stringArray)
{
    sum += Convert.ToInt32(element);
}

MessageBox.Show("Sum of your numbers is " + sum);

Upvotes: 1

Related Questions