[英]How do I call a Method from another file in OnCommand of my asp:Button? asp.net C#
I want to tidy up my Default.aspx and tried to move the 'actionlistener' (I know that might not be the right name in C#) of my buttons into a file I've called 'DefaultCodeBehind.cs'. 我想整理一下Default.aspx,并尝试将按钮的“ actionlistener”(我知道在C#中可能不是正确的名称)移动到一个名为“ DefaultCodeBehind.cs”的文件中。
I declared the CodeBehind file on top of Default.aspx like so: 我在Default.aspx顶部声明了CodeBehind文件,如下所示:
<%@ Page Language="C#" CodeBehind="DefaultCodeBehind.cs" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
This is the button (also in Default.aspx): 这是按钮(也在Default.aspx中):
<asp:Button runat="server" type="button" id="contSec5" CommandName="contSec5" OnCommand="ToggleDivPage" CssClass="button_menubar" text="Section 5" />
And this is the actionlistener/method in DefaultCodeBehind.cs: 这是DefaultCodeBehind.cs中的actionlistener /方法:
void ToggleDivPage(object sender, CommandEventArgs e)
{
code...
}
This is the error appearing when trying to execute the code: 这是尝试执行代码时出现的错误:
CS1061: 'default_aspx' does not contain a definition for 'ToggleDivPage' and no extension method 'ToggleDivPage' accepting a first argument of type 'default_aspx' could be found (are you missing a using directive or an assembly reference?)
CS1061:“ default_aspx”不包含“ ToggleDivPage”的定义,找不到扩展方法“ ToggleDivPage”,该扩展方法接受“ default_aspx”类型的第一个参数(是否缺少using指令或程序集引用?)
I also tried to call the method like so: 我也尝试这样调用该方法:
<asp:Button runat="server" type="button" id="contSec5" CommandName="contSec5" OnCommand="DefaultCodeBehind.ToggleDivPage" CssClass="button_menubar" text="Section 5" />
But I wasn't really expecting this to work anyway. 但是我并不是真的希望这个能够成功。 (I'm pretty new to C# and especially to asp.net, what might explain this funny attempt.)
(对于C#尤其是asp.net,我还很陌生,这可能解释了这一有趣的尝试。)
Do I have to declare CodeBehind different or isn't it even possible to move the actionlisteners outside Default.aspx. 我是否必须将CodeBehind声明为不同,否则是否有可能将动作侦听器移到Default.aspx之外。
Thanks in advance. 提前致谢。
Best regards, 最好的祝福,
Lars 拉尔斯
Several minutes after I posted this question, I stumbled upon the answer myself. 发布此问题几分钟后,我自己偶然发现了答案。 I completely overlooked the
CodeFile
tag. 我完全忽略了
CodeFile
标签。 Therefore ToggleDivPage
couldn't be found in CodeBehind
, because it had to be in Default.aspx.cs
. 因此
ToggleDivPage
不能在找到CodeBehind
,因为它必须在Default.aspx.cs
。 Moving it and of course making it public
solved my problem. 移动它,当然使其
public
解决了我的问题。 A thanks to @Stefan and @James Thorpe who solved the problem as well. 感谢@Stefan和@James Thorpe也解决了这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.