Event and Handlers

The last Hello World program is not much fun even though it has gotten us started with our first ASP.NET program, we will modify it to display the current date. To do this we will have to use the work with event and handler.

To do this I remove the Text proper from the Label box.

<asp:Label ID="Label1" runat="server"></asp:Label> 

Open to the Code-behind Default.aspx.cs


And write the below line of code at  the Page_Load page event

Label1.Text = DateTime.Today.ToLongDateString();

 

Here is the complete code

Defaul.aspx.cs
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="MyWeb._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
	<form id="form1" runat="server">
	<div>
		Today's date is <asp:Label ID="Label1" runat="server"></asp:Label> 
	</div>
</form>
</body>
</html>

 

Default.aspx.cs.

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

namespace MyWeb
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Label1.Text = DateTime.Today.ToLongDateString();
        }
    }
}

 

The preview

 

Next »