NullReferenceException on User Control handle
-
09-06-2019 - |
Question
I have an Asp.NET application (VS2008, Framework 2.0). When I try to set a property on one of the user controls like
myUserControl.SomeProperty = someValue;
I get a NullReferenceException
. When I debug, I found out that myUserControl
is null. How is it possible that a user control handle is null? How do I fix this or how do I find what causes this?
Solution
Where are you trying to access the property? If you are in onInit, the control may not be loaded yet.
OTHER TIPS
Where exactly in the code are you attempting to do this? It is possible that you are attempting to access the control too early in the page lifecycle and it has not been instantiated yet.
If you created the UserControl during runtime (through ControlCollection.Add), you need to create it on postback too.
Another case can be your UserControl does not match the designer.cs page
I was trying to set the property from markup on an outside user control. When I took the property to OnLoad, it worked.