views:

34

answers:

3

Here is my simple class, where i inherit from UserControl.

public class Test:System.Web.UI.UserControl
{
    public void BindGrid()
    {
        Response.Write(IsPostBack);
    }
}

Which i call from the Page_Load event

protected void Page_Load(object sender, EventArgs e)
{
  new Test().BindGrid();
}

But i get a null reference exception if i try to call any of UserControl's inerited properies (ispostback, request etc etc)

Any ideas why this is happening?

Edit:

It seems to work if replace the 'ispostback' response.write() inside the OnLoad method of Test?

+1  A: 

is this a true UserControl? else i would inherit control instead, is the usercontrol placed on a asp.net page when you call the functions or is it just instated and called?

Petoj
+1  A: 

Your class is not processed as the user control. Hence there is no "IsPostBack" and another properties. They are just null. You should register your class on the page so that this class will be the part aspx page

B-Rain
+1  A: 

Properties like IsPostback depend on the Page where the user control is hosted, well, should be hosted, as your example does not add the user control to the Controls collection of the Page, which explains the crash.

Timores
Interesting - i did not realise it had to be added to a control collection in the page to populate those properties. Still don't fully understand why/how this works?
maxp
Because a Control has a Page property (the hosting page) and the IsPostback property (and others) is handled by the Page. Adding the Control to the control collection gets the Page property set on the control
Timores