Search code examples
.netwebformsrenderingcode-behind

How the structure of the code behind file working in the web form? - .NET


I'm learing .NET and I'm wondering about the structure of the code behind file in web forms.

The structure is always:

using System;
namespace TestWebApp1
{
    public partial class MyPage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
    }
}

Is it so that .NET always looks for the MyPage (filename) class en uses this to render the page?

Or can I have a file called Name1 and than use the class Name2 : System.Web.UI.Page for rendering the page? If yes, how do I get that working? Because I now get an exception?


Solution

  • Look at the top of your .aspx file :

    <%@ Page Language="C#" CodeFile="MyPage.aspx.cs" Inherits="MyPage" %>
    

    The CodeFile attribute represents the physical file to use for code behind. The Inherits attribute represents the partial class that will be inherited for code behind.

    So if you rename your partial class inside the code behind, you have to rename it in the inherits attribute as well.