Search code examples
c#wpftextboxline-breakstryparse

Spliting numerical input by linebreak in a textbox, doing some math on it, and outputting results in a new textbox


I'm attempting to create a wpf app that takes a list of numerical values, separated by line breaks, in one textbox. You click a button, and it outputs the new numerical values into a second textbox. I'm running into issues separating the values the user inputs.

For this to make more sense the first textbox is called inputBox and the second textbox is called outputBox. The button will have event mathClick. We will have the button just multiply the number by 2.

This is what I have:

    private void mathClick(object sender, RoutedEventArgs e)
        {           
            foreach (var num in inputBox.Text.Split("\n"))
            {
                if(double.TryParse(num, out double value))
                {
                    outputBox.Text = Convert.ToString(value * 2);
                }
            }
        }

This is what happens

inputBox:

7.02

18.98

3.51

outputBox:

7.02

It's only grabbing the last value in the textbox and doing the arithmetic on that.

This is the scenario I'm trying to achieve

inputBox:

7.02

18.98

3.51

outputBox:

14.04

37.96

7.02

Any help is greatly appreciated.


Solution

  • I figured it out, if any other beginners like me come across this - you must remember Textbox will return a string. The way I fixed it was to split the input at the linebreak and store it in a string array

    string[] stringNum = textbox.text.split("\n");
    

    Then you can use a for loop to convert this array of type string to a double and print the double to your textbox with a linebreak each time the loop runs.

    for (int i = 0; i < stringNum.Length; i++)
    {
        double num = Convert.ToDouble(stringNum[i]);
        textbox.text += Convert.ToString($"{num}\n");
    }
    

    Hope this helps someone else, thanks.