简体   繁体   中英

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'.

I declared the CodeBehind file on top of Default.aspx like so:

<%@ Page Language="C#" CodeBehind="DefaultCodeBehind.cs" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

This is the button (also in 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:

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?)

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.)

Do I have to declare CodeBehind different or isn't it even possible to move the actionlisteners outside 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. Therefore ToggleDivPage couldn't be found in CodeBehind , because it had to be in Default.aspx.cs . Moving it and of course making it public solved my problem. A thanks to @Stefan and @James Thorpe who solved the problem as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM