Wednesday, January 21, 2015

ASP.NET UserControl.Visible = true failing

Today I came across a situation where I was trying to set an ASP.NET UserControl to be Control.Visible = true, and try as I might, the call was failing. Here's what I did in the immediate window in Visual Studio.

MyControl.Visible = true;
MyControl.Visible; // output: false;


I almost bashed my head against my keyboard. It turns out that 'Visible' behaves like a property, not a field. You can set it to true, but it only returns true if the control is actually visible on the page. In my case, the control was not visible because I had set

ParentControl.Visible = false;

on Page_Load. I was trying to set MyControl.Visible to true on postback, but since ParentControl had not been explicitly set to true, MyControl.Visible was still returning false. I set

ParentControl.Visible = true;

et voila! MyControl.Visible immediately returned true.


Lesson: if you're trying to set your control's Visible property to true, and it's still returning false, check the parent controls and see whether those might not have their visibility set to false.

0 comments:

Post a Comment