2
votes

I need help with this, I'm trying to set the "display:none" into "display:block" in my div tag which is in the Content Page. When i do the code below, the HtmlGenericControl class keeps on giving error "Object reference not set to an instance of an object" because he can't find the "divSignin" (the id of my div tag) but it's there as presented in the code: Please help.

Is something wrong with my implementation of HtmlGenericControl?

Here's the code in my Content page:

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <div class="col-md-4" id="divSignin" style="display:none" runat="server">
    </div>
</asp:Content>

And Here's my code behind in my Master Page:

protected void lbtnRegister_Click(object sender, EventArgs e)
{
    HtmlGenericControl myObject = Master.FindControl("ContentPlaceHolder1").FindControl("divSignin") as HtmlGenericControl;

   //HtmlGenericControl myObject;
   // myObject = (HtmlGenericControl)ContentPlaceHolder1.FindControl("divSignin");
   // myObject.Style.Add("display", "block");
}

The comment part in code behind is the other thing i tried which returns the same thing (Null).

3

3 Answers

2
votes

Can you please try below,

protected void lbtnRegister_Click(object sender, EventArgs e)
{
    HtmlGenericControl myObject = ContentPlaceHolder1.FindControl("divSignin") as HtmlGenericControl;
}
2
votes

If the handler for click event is located on the MasterPage, you should use:

HtmlGenericControl control = this.FindControl("MainContent").FindControl("divSignin") as HtmlGenericControl

your solution would be working if the handler was in the code-behind for the Page, where you have your div. But in that case, you could also get the control like this:

HtmlGenericControl control = this.divSignin;
1
votes

So I found the answer to my question. My code is correct, and there's really nothing wrong with the code behind. Only that I created a new div (Please refer to the below html:)

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div class="col-md-4">
   <div id="someID" runat="server" style="display:block">

   </div>
</div>

And this is my code behind in my MasterPage:

protected void lbtnRegister_Click(object sender, EventArgs e)
    {
        HtmlGenericControl myObject = this.FindControl("ContentPlaceHolder1").FindControl("divShow") as HtmlGenericControl;
        myObject.Style.Add("display", "none");
    }

I'm not sure what causes the null reference, but I'm guessing that having a class inside the div caused my problem here. Thanks for the reply guys. I appreciate your efforts and time