ASP.NET - "Object not set to instance of an object " why am I getting this error

Asked By TommySG SG on 23-Jul-15 11:16 AM
So I have a validator in the aspx page

    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="RequiredFieldValidator" Enabled="True"  ControlToValidate="Date"  ></asp:RequiredFieldValidator>

in the code behind I want do disable it base on the role of the user


   if (User.IsInRole("Admin"))
    {
    RequiredFieldValidator cecvaliddate = (RequiredFieldValidator)FindControl("RequiredFieldValidator1");

    cecvaliddate.Enabled = false;

    }

when I run this I get the error "Object reference not set to an instance of an object." Highlighting the line
  "cecvaliddate.Enabled = false;"


By the way this is with C# and Visual studio 2010
Robbe Morris replied to TommySG SG on 23-Jul-15 01:47 PM
Why do you need FindControl?

Why not just access it by ID?

this.RequiredValidator1.Enabled = false;
TommySG SG replied to Robbe Morris on 23-Jul-15 02:03 PM
Because it's inside a Formview that is within an Update Panel I tried (RequiredFieldValidator)Formview.FindControl("RequiredFieldValidator1");  but still same error
Robbe Morris replied to TommySG SG on 23-Jul-15 02:14 PM
Ah,

I believe the top rated answer here should resolve it for you.  FormViews and UpdatePanels are handled a little differently.

http://stackoverflow.com/questions/15232907/asp-net-cannot-access-update-panel-inside-login-view-inside-formview-controls
TommySG SG replied to Robbe Morris on 23-Jul-15 02:40 PM
I modified the code to match the answer that guy gave, but still the same error, instead of insert mode in the formview I have Edit mode, and instead of a loging view, is an update panel. I changed his code to match those but still same error