1

I have a user control. webcontrol.ascx

<div runat="server" id="abc"></div>

in webcontrol.ascx.cs, i have a method to add class name

public void ABCmethod(){ abc.Attributes["class"] = "className" };

When I create it in my default.aspx declaratively, <uc:WebControl runat="server" id=wc1" />, this ABCmethod doesn't throw any exception.

But when I created it programmatically,

protected void Page_Load(object sender, EventArgs e)
    {
        WebControl wc1 = new WebControl();
        wc1.ABCmethod();
    }

this throws an error. Saying that the abc is an Object reference not set to an instance of an object.

2
  • Could you post the code of where you are creating the webcontrol? i.e. are you creating the control on page load and then trying to access the method in another event on the page? Commented Sep 8, 2013 at 16:54
  • @Damon I created programmatically in another page during Page_Load event. Do you imply that, I have created the wc1, but the wc1 hasn't execute Init or Page_Load yet, thus, I get the div is not set to an object? Commented Sep 8, 2013 at 16:56

1 Answer 1

1

I think you need to use the LoadControl method from the example here

More specifically, you need something like this code:

protected void Page_Load(object sender, EventArgs e)
{
    WebControl myControl = (WebControl)LoadControl("~/Controls/webControl");
    myControl.ABCMethod();
}

You will also need to add the control to a placeholder control otherwise the control won't be visible.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.