Public Methods inside User control c# .net

2019-07-31 05:03发布

How can invoke user control's public method from within the page?

I load the control dynamically inside OnInit on the page.Any ideas? For some reason I am getting a build error that says that the method doesn't exist, even though it's public. Starting to think that user controls are not worth all the hassle.

5条回答
ら.Afraid
2楼-- · 2019-07-31 05:33

Without sample code it's hard to say for sure, but I'm guessing you need to cast your reference to the UserControl to the specific type of your custom control. For example, if your UserControl is of type "PersonControl", then your code would look something like this:

PersonControl ctl = (PersonControl)LoadControl("PersonControl.ascx");
ctl.DoCustomMethod();
查看更多
老娘就宠你
3楼-- · 2019-07-31 05:37

If your class is inheriting from UserControl, be sure that when you're accessing it, like others have said, you're casting it correctly. For instance:

public MyControl : UserControl
{
    public void MyMethod(){...}
}

in your form:

private MyControl mycontrol = new MyControl();
private void MainForm()
{
    this.Controls.Add(mycontrol);

    InitializeComponent();
}

private void DoStuff()
{
    ((MyControl)mycontrol).MyMethod();
}
查看更多
一纸荒年 Trace。
4楼-- · 2019-07-31 05:44

Are you casting the User Control to the correct type?

查看更多
看我几分像从前
5楼-- · 2019-07-31 05:50

Mike's answer is how it's done, but Visual Studio can be a bit wonky about detecting the UserControl class, and complain that the type doesn't exist. In those situations I've have to add a <% @Reference %> tag on the page to force it to recognize, even though it may be referenced in the web.config.

查看更多
来,给爷笑一个
6楼-- · 2019-07-31 05:53

You've said

Control fracTemplateCtrl = 
   (FracTemplateCtrl)LoadControl("FracTemplateCtrl.ascx")
fracTemplateCtrl.TestMethod();

you need to say

FracTemplateCtrl fracTemplateCtrl =
   (FracTemplateCtrl)LoadControl("FracTemplateCtrl.ascx")
fracTemplateCtrl.TestMethod();

Note that fracTemplateCtrl is declared as a FracTemplateCtrl, so visual studio knows that it has a TestMethod(). When it is declared as a Control, visual studio can't make this assumption.

查看更多
登录 后发表回答