Writing Some Code
4 Feb 2008 @ 02:04PM

Updated: 22 Jan 2010 @ 02:06PM
Let's go ahead and dive in to do some quick coding. On the right side, click the plus next to Default.aspx. You should see a Default.aspx.cs listed. Notice that this is the CodeFile that's specified at the top of Default.aspx. When you open it you'll get a display similar to this:


The Default Code-Behind Page


The first thing you'll notice is a bunch of using commands. These are namespaces that we're importing into the application. Suffice it to say that each of these namespaces gives us access to different commands to do stuff. The System namespace is a basic namespace with alot of very common commands. Go ahead and delete them all except using System. We'll add them as we need to.

Next you'll see the line that begins with public partial class. Notice that _Default is the same class that our Default.aspx page inherits. Basically it means that when Default.aspx loads, it includes this 'class'. For our purposes, a class just holds code. The portion that reads _Default : System.Web.UI.Page means that the _Default class inherits another class called System.Web.UI.Page. You can safely ignore that for now.

Within the _Default class you'll notice a line that reads protected void Page_Load(object sender, EventArgs e). This is a method. In fact, this is the Page_Load method. This method executes automatically whenever the web page runs. This is a good place for us to put our code.

Let's start by putting the cursor within the Page_Load method. Now type the following line:


Our First Line of Code


If you look back at the Default.aspx page, you'll notice that the runat="server" that's in the body of the html page has an id of form1. By putting form1. in our line of code, we are addressing this item. We are then adding InnerHtml at the end. This tells C# to take the string that follows and insert it into the item as HTML. Lastly we're making a string that reads "Hi there world.". The semicolon at the end lets C# know that we're done with that command. Notice the double quotes enclosing our string. Unlike in PHP, single quotes will not work.

Go ahead and save these changes, then load the page up in Internet Explorer by navigating to http://127.0.0.1/FirstSite. You should see the string we entered printed out on the page.
Comments (0)