Ignora collegamentiHome / Blog

Blog


A simple example showing how to run the Page_Load and PostBack event in an ASP.NET page

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    /// <summary>
    /// This method is executed every time the page is loaded by the browser
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            LabelMessage_PL.Text = "<b>This page was loaded on: </b>" + this.GetDateTime();
    }

    /// <summary>
    /// This method is executed when the button is clicked
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void ButtonRefresh_Click(object sender, EventArgs e)
    {
        LabelMessage_PB.Text = "<b>The click of the button has been performed: </b>" + this.GetDateTime();
    }

    /// <summary>
    /// This private method retrieves the date and time of the server and returns a formatted message
    /// </summary>
    private string GetDateTime()
    {
        return DateTime.Now.Date.ToShortDateString() +
                        ", and " +
                        "now is: " + DateTime.Now.ToLongTimeString();
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Test: Page_Load and PostBack Event in ASP.NET</title>
</head>
<body>
    <form id="formMain" runat="server">
    <div>
        <asp:Label ID="LabelMessage_PL" runat="server"></asp:Label>
        <br />
        <br />
        <asp:Label ID="LabelMessage_PB" runat="server"></asp:Label>
        <br />
        <br />
        <asp:Button ID="ButtonRefresh" runat="server" Text="Get current time" OnClick="ButtonRefresh_Click" />
    </div>
    </form>
</body>
</html>

 

When the page is loaded for the first time LabelMessage_PL displays the current date and time.

When the button is clicked, LabelMessage_PB displays the date and time at which the event is intercepted; LabelMessage_PL continues to display the date and time above.



Category: ASP.NET