C# UserControl Visible Property Not Changing

cuser-controlswinforms

Debug.WriteLine(ucFollow.Visible);
ucFollow.Visible = true;
Debug.WriteLine(ucFollow.Visible);

ucFollow is a custom UserControl, nothing fancy. The above code prints out:

False
False

Worst part is, this does toggle the actual visibility of the UserControl (i.e. ucFollow does appear once this code is called), but it seems somehow that the Visible property isn't … well, visible on the backend, and doesn't reflect the change, even though the UI itself does.

I don't even know where to begin troubleshooting this. Does anyone have any ideas as to what could remotely cause this kind of craziness?

Edit: This is with a standard C# WinForm in Visual Studio 2010.

Best Answer

I didn't break C#! :)

Turns out the culprit was the Form.Visible property. Before Form.Visible is set to true, any and all controls on the form will be invisible (Visible = false) no matter what.

However, you can still set Visible properties - they just won't take effect until the Form.Visible property is set to true.

In other words, when I called ucFollow.Visible = true, my program was indeed registering it - however, at that point in the code, ucFollow's parent Form.Visible was still false. Therefore, both the Debugger and my print statements recognized, "Hey, this control's parent form is still not visible, so this control is not visible. Period."

As soon as the form was made visible, all the changes took effect and everything worked great.

Moral of the story: Don't rely on the Visibility properties of your controls unless the form containing them is already visible and running.