Please let other users know how useful this tip is by rating it below. Do you have a tip or code of your own you'd like to share? Submit it here.
Code behind is a new feature of ASP.NET that lets you separate code and presentation in different files. With this kind of technique you could write a presentation in an .aspx file and the code could be any .NET-compatible language (C#, VB.NET, etc.). The benefit is that it becomes easy to manage code and the presentation of it, while the work can be distributed -- people good at presentation can work on that part of the application and the programmer could work just on the coding part.
There are actually two physical files on the disk where a tag in .aspx files tells the name of the class and the name of the physical file. Note: Inherit tells the name of the class in the code behind file and SCR is source file. When the default.aspx loads, you see that page_load event is called in the default.vb file, and, similarly, on click the button we see the code gets called from the default.vb file.
<%@Page language="vb" inherits="CodeBehindClass" src="Default.vb" %> <form runat="server"> <asp:button id="button1" text="button 1" onclick="button1_click" runat="server" /> <asp:label id="lbl" text="label and button in the aspx file " runat="server" /> </form>
imports system imports system.web imports system.web.ui imports system.web.ui.webcontrols imports system.web.ui.htmlcontrols public class CodeBehindClass Inherits System.web.ui.page public lbl as label sub Page_Load(sender as object,e as eventargs) lbl.Text = "page load in Code Behind" end sub sub Button1_click(sender as object,e as eventargs) lbl.text = "Button click in Code Behind" end sub end class
Save both the pages to wwwroot and run in Default.aspx in the browser.
This was first published in June 2003