Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing label.visibility with a method - Why won't it hide?

I want to be able to set any label's visibility to true or false with a method. I have this code:

private void Change_Visible(Label toBeChanged)
{
    if (toBeChanged.Visible == false)
    {
        toBeChanged.Visible = true;
    }
    else
    {
        toBeChanged.Visible = false;
    }
    toBeChanged.Refresh();
}

I call to this code with:

    Change_Visible(myLabel);
    //
    // Do other things
    //
    Change_Visible(myLabel);

In my specific example, myLabel is set to not be visible at the load of my form. After the first call to Change_Visible it becomes visible, but after the second call to Change_Visible nothing happens. Can you help me make it disappear?

I have already tried some other logics looking for a solution - for example:

private void Change_Visible(Label toBeChanged)
{
    if (toBeChanged.Visible == false)
    {
        toBeChanged.Visible = true;
        toBeChanged.Refresh();
        return;
    }
    if (toBeChanged.Visible == true)
    {
        toBeChanged.Visible = false;
        toBeChanged.Refresh();
        return;
    }
}

I have not come to any conclusions. I am learning C# by myself and started just a few weeks ago, so maybe I am missing something obvious. Thanks for your help!

like image 726
Elder Taylor Avatar asked Sep 16 '25 05:09

Elder Taylor


1 Answers

The label won't actually become invisible to the user until its Parent redraws its background, painting over the pixels formerly drawn by the label control. This doesn't happen in your code, painting only occurs when the main thread goes idle and re-enters the message loop. It isn't idle, it is executing those "other things".

A workaround is to ask the parent to paint itself early:

myLabel.Visible = false;
this.Update();
//
// Do other things
//
myLabel.Visible = true;

Code that runs long enough to require feedback like this ought to be run in a worker thread instead. Use a BackgroundWorker or Task.

like image 75
Hans Passant Avatar answered Sep 19 '25 13:09

Hans Passant