Search code examples
asp.netnullreferenceexceptionobject-reference

How to check if Panel has an instance of an object


in code-behind I declare a Panel:

Panel customPanel = new Panel(); // or simply Panel customPanel;

Then I can either assign it to an existing panel or not:

if (blablabla) customPanel = otherPanel;

Then I need to focus on the customPanel if it is assigned:

customPanel.focus(); // Object reference not set to an instance of an object

How to check if customPanel is set to an instance?

if (customPanel != null) // the same

It only works when "blablabla" condition is true and customPanel is assigned to a panel.


Solution

  • you can use try catch block as following

    try
    {
        customPanel.focus();
    }
    catch(Exception nullObjectException)
    {
        //do error handling 
    }