Object reference not set to an instance of an object

I have the following code that keeps giving me an error "System.NullReferenceException: Object reference not set to an instance of an object." on the line "btnProductA.Attributes.Add("onmouseover", "imageOn();");".  The code (giving the error) is in a content page of a master page.  How can I resolve this?

Thanks very much in advance!
Here's the code in the Content Page (which is embedded within a Master Page):
<asp:Content ID="Content1" ContentPlaceHolderID="ProductImages" Runat="Server">
    <table border="0" cellpadding="0" cellspacing="0">
                <asp:ImageButton ID="btnProductA" runat="server" ImageUrl="images/ProductA.gif" BorderWidth="0" />
                  Click on product picture.
Here's the code behind of the Content Page:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
public partial class customers : System.Web.UI.Page
    protected void Page_Load(object sender, EventArgs e)
        ImageButton btnProductA = (ImageButton)FindControl("btnProductA");
        btnProductA.Attributes.Add("onmouseover", "imageOn();");
        btnProductA.Attributes.Add("onmouseout", "imageOff();");

Open in new window

Who is Participating?
WebAppDeveloperConnect With a Mentor Author Commented:
The solutions is: I didn't need this line "ImageButton btnProductA = (ImageButton)FindControl("btnProductA");"    All I needed was: "btnProductA.Attributes.Add("onmouseover", "imageOn();");"
Obviously the line ImageButton btnProductA = (ImageButton)FindControl("btnProductA");
does not return an object. I.e the button is nothing. Probably there is some problem with the FindControl method.
WebAppDeveloperAuthor Commented:

So how can I fix it?
Good question. I don't know what the FindControl function is doing exactly and how it work. Honestly speaking, I have no idea how control search works for web pages - I work mainly with winforms.

If FindControl is a custom method - try to debug it and see why it returns null.

But probably it would be a good idea to set a break point at
"The issue is no longer an issue"  - I like that. So, what was the reason? Found the button eventually?
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.