0

I'm trying to update a labels text. When the original text contains multiple lines and I update the text to something with a single line the old multiple lines are still visible even when the text updates on the top line. Here is an example. How can I fix this?

PhotoText.Text = "Testing Some\nCode Out\nRight Now!"; //This shows 3 lines
PhotoText.Refresh();    
Thread.Sleep(1000);
PhotoText.Text = "New Text!"; //This shows 1 lines
PhotoText.Refresh();
Thread.Sleep(1000);
Emond
  • 50,210
  • 11
  • 84
  • 115
user2843198
  • 95
  • 1
  • 9
  • WHat platform are you working on? WinForms, WPF, UWP? – danvy Jan 02 '16 at 13:19
  • I'm working with WinForms – user2843198 Jan 02 '16 at 13:20
  • 2
    Where is this code called? It works when I call it from a Button click. – danvy Jan 02 '16 at 13:27
  • 2
    You have the label's AutoSize property set to True. The shorter text makes the label smaller, the old pixels can only be overpainted when the label's Parent repaints itself. So you also need PhotoText.Parent.Update(). Just don't hang the UI thread and you won't have problems like this. – Hans Passant Jan 02 '16 at 13:42
  • Your code is perfectly find in my `WinForm` using default `Label` settings. Perhaps you may also want to post your `Label`'s property settings? – Ian Jan 02 '16 at 15:49

3 Answers3

1

You should not block UI thread. Run long running tasks separately:

private void button46_Click(object sender, EventArgs ee)
{            
    new Task(() =>
    {
        this.Invoke(new EventHandler((o, e) => PhotoText.Text = "Testing Some\nCode Out\nRight Now!"));           
        Thread.Sleep(1000);
        this.Invoke(new EventHandler((o, e) => PhotoText.Text = "New Text!"));
        Thread.Sleep(1000);
    }, TaskCreationOptions.LongRunning).Start();
}

this is a form, the Invoke runs PhotoText.Text =... on UI thread. You can also use this.BeginInvoke even without EndInvoke (see more).

Community
  • 1
  • 1
Antonín Lejsek
  • 6,003
  • 2
  • 16
  • 18
-2

Try to call

this.Refresh();
Application.DoEvents();

between each update.

danvy
  • 2,085
  • 12
  • 17
-3

Try doing it with string

PhotoText.Text = "Testing Some\nCode Out\nRight Now!"; //This shows 3 lines
PhotoText.Refresh();    
Thread.Sleep(1000);
string phototext="New Text!";
PhotoText.Text = phototext; //This shows 1 lines
PhotoText.Refresh();
Thread.Sleep(1000);
stan.steve
  • 111
  • 10