用户控件内的公共方法 c# .net
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/603419/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Public Methods inside User control c# .net
提问by sarsnake
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.
我在页面上的 OnInit 中动态加载控件。有任何想法吗?出于某种原因,我收到一个构建错误,指出该方法不存在,即使它是公开的。开始认为用户控件不值得所有麻烦。
采纳答案by Daniel LeCheminant
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.
请注意,fracTemplateCtrl is
声明为 a FracTemplateCtrl
,因此 Visual Studio 知道它有一个TestMethod()
. 当它被声明为 a 时Control
,visual studio 不能做出这个假设。
回答by Nick
Are you casting the User Control to the correct type?
您是否将用户控件转换为正确的类型?
回答by Mike Powell
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:
没有示例代码很难确定,但我猜您需要将对 UserControl 的引用转换为自定义控件的特定类型。例如,如果您的 UserControl 是“PersonControl”类型,那么您的代码将如下所示:
PersonControl ctl = (PersonControl)LoadControl("PersonControl.ascx");
ctl.DoCustomMethod();
回答by Steven Evers
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:
如果您的类是从 UserControl 继承的,请确保您在访问它时,就像其他人所说的那样,正确地转换了它。例如:
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();
}
回答by Adam Lassek
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.
Mike 的回答是它是如何完成的,但 Visual Studio 在检测 UserControl 类方面可能有点不稳定,并抱怨该类型不存在。在这些情况下,我必须<% @Reference %>
在页面上添加一个标签来强制它识别,即使它可能在 web.config 中被引用。