Harold_Finch
Harold_Finch

Reputation: 722

Prevent textbox from overwriting previous data

I have two if-else conditions which will display some text on a Windows Forms textbox. This textbox has text set to it from a different thread other than the UI thread.

Context:

 delegate void SetTextCallback(string text);

 private void SetText(string text)
 {
     if (this.txtMessages.InvokeRequired)
     {
         SetTextCallback d = new SetTextCallback(SetText);
         this.Invoke(d, new object[] { text });
     }
     else
     {
         this.txtMessages.Text = text;
     }
 }

 private void setTextFunc()
 {
     if(this condition is true)
     {
         setText("Hello from text 1" + Environment.NewLine);
     }
     else
     {
         setText("Hello from text 2" + Environment.NewLine);
     }
}

Now the problem is that when Hello from text 2 text gets displayed, it overwrites the first text. I want it to go below and keep the first text. How can I achieve this?

I thought about using a list collection as so:

List<string> listOfStrings = new List<string>();
listOfStrings.Add("Hello from text 1");
listOfStrings.Add("Hello from text 2");

Then iterating through this list collection. Will that do?

foreach(string x in listOfStrings)
{
    MessageBox.Show(x);
}

Any suggestions? I considered a RichTextBox but seeing as I won't be editing the text at runtime, I see no need for it.

Upvotes: 1

Views: 593

Answers (1)

Rob
Rob

Reputation: 45761

The problem you have is that:

this.txtMessages.Text = text;

In your setText method replaces the content of the Text property of your text field. If you want to add to the existing content, you should replace the code with something along the lines of:

this.txtMessages.Text = this.txtMessages.Text + text;

As your code suggests (thanks to the addition of Environment.NewLine in setTextFunc) that you always want to delimit the newly added text with a line-break, consider adding a new function along the lines of:

private void AppendText(string text)
{
    // Code to trigger the Invoke here
    else
    {
        this.txtMessages.Text = this.txtMessages.Text + Environment.newLine + text;
    }
}

Doing this also allows you to encapsulate the behaviour of "add text with a new line" into a single method - at the moment your setTextFunc method has a really small amount of repeated code (adding Environment.NewLine) which you can elide by doing this.

Upvotes: 6

Related Questions