Minosum
Minosum

Reputation: 23

Adding a newline to textbox in a loop structure

I'm working on my assignment and I've hit a roadblock, been trying to figure out where I'm going wrong in this code. I've searched a fair bit but couldn't find a solution. This is my code.

float Counter = 5.0f;
while (Counter < 24.0f)
{
    string Output = "";
    Output += Counter;
    txtAvgTemp.Text = Output.ToString();
    Counter += 1.5f;
    txtAvgTemp.Text.Split('\n');
}

my output data just shows 23, it goes through the loop and replaces all the previous string, I would like it too start from 5, print, then add 1.5, print. any help would be appreciated thank you.

Thanks for all the reponses it worked!! I have to add a calculation as part of the counter. but its giving me a unhandled error, where im trying to float.parse(volume) not sure why here is the code.

`string AvgTempOutput = ""; string volume; float Counter = 5.0f; float heatingCost;

    while (Counter < 24.0f)
    {
        AvgTempOutput += Counter;
        txtAvgTemp.Text += Counter.ToString() + "\r\n";

        volume = txtVolume.Text;
        heatingCost = (25.0f - Counter) * float.Parse(volume);
        txtTableDollars.Text = heatingCost.ToString() + "r\n";

        Counter += 1.5f;


    }`

Upvotes: 1

Views: 1576

Answers (2)

Uthman Rahimi
Uthman Rahimi

Reputation: 708

you should declare out while your variable ,like this :

string Output = "";
while (Counter < 24.0f)
{

    Output += Counter;
    txtAvgTemp.Text = Output.ToString();
    Counter += 1.5f;
    txtAvgTemp.Text.Split('\n');
}

in your code , each time Output clear when start new loop . its better replace String with StringBuilder Like this :

StringBuilder Output=new StringBuilder("");

Upvotes: 0

Ghasem
Ghasem

Reputation: 15573

You are replacing your text on each loop instead of adding new line to it as your are mentioning. Change the code like this

float Counter = 5.0f;
string Output = "";
while (Counter < 24.0f)
{
    Output += Counter;
    txtAvgTemp.Text += "\r\n" + Output.ToString(); //Appending the text
    Counter += 1.5f;
}

Upvotes: 2

Related Questions