0

How can I call a method from my user control(.ascx) file in one of the class file(.cs file)

Any ideas, how can I do this?

4
  • 1
    Just out of curiosity; Why? Extremely bad practice. Commented Oct 19, 2015 at 13:12
  • Its one of my requirement, can't roll back now. How can this be done? Commented Oct 19, 2015 at 13:16
  • give a reference to an instance of user-control to the class and make the user-control method public Commented Oct 19, 2015 at 13:21
  • Can you show me how? Commented Oct 19, 2015 at 13:25

1 Answer 1

2

Give a reference to an instance of user-control to the class and make the user-control method public.

public class MyUserControl : UserControl
{
  public void MyUCMethod()
  {
  }
}

public class MyClass
{
  private MyUserControl myUC;
  public MyClass(MyUserControl uc)
  {
    myUC = uc;
  }
  public void MyClassMethod()
  {
    myUC.MyUCMethod();
  }
}

In the page class:

protected void Page_Load(object sender, EventArgs e)
{
  MyUserControl uc = (MyUserControl)LoadControl("MyUserControl.ascx");
  Controls.Add(uc);

  MyClass c = new MyClass(uc);
  c.MyClassMethod();
}
Sign up to request clarification or add additional context in comments.

4 Comments

Will this line "MyUserControl uc = (MyUserControl)LoadControl("MyUserControl.ascx");" wont give error in class file in app_code folder.
? LoadControl is a method of System.Web.UI.Page class.
But i am calling user control method from class file not an aspx page.
Having a user-control only makes sense in the context of a web page.

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.