Changing label.visibility with a method - Why won't it hide?
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.
Related videos on Youtube
Elder Taylor
Updated on May 29, 2020Comments
-
Elder Taylor almost 4 years
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!
-
Parv Sharma over 10 yearsmake sure you are not blocking UI thread after second call to change_visible
-
User 12345678 over 10 yearsEverything appears to be fine - could you introduce some more context?. The Label will actually be invalidated when the
Label.Visible
property is set which means callingLabel.Refresh
is actually redundant here. You could actually replace the entire method body withreturn toBeChanged.Visible = !toBeChanged.Visible;
. -
Elder Taylor over 10 yearsIt didn't show the label the first time until I added the Label.Refresh() line, that is why it is there.
-
-
stayinwett over 10 yearsYeah, I guess that should be expected behavior
-
Elder Taylor over 10 yearsAdding this.Update(); worked perfectly. I also looked into BackgroundWorker and think that would help a lot with what I am doing. Thanks for the answer!