ASP.NET LiteralControl

ASP.NET web programming framework

You want to use LiteralControl in your ASP.NET application. This is a way to embed a comment or text in the HTML source of each ASP.NET page rendered. Here we see an example of this web control and add a timestamp to our pages, using the C# programming language.

This C# program uses the LiteralControl type from ASP.NET. It adds comments.

Example

Note

First, here is how to get the current time in the best format, which keeps the comments small, and also how to use LiteralControl to add a comment to your pages. You may want to look at my asp:Literal control article, but in any case what we need to do here is create a new asp:Literal and append it to the bottom of the .aspx page.

Code that uses LiteralControl [C#]

static public string TimeString()
{
    return DateTime.Now.ToString("h:mm:ss");
}

protected void Page_Load(object sender, EventArgs e)
{
    LiteralControl literal = new LiteralControl("<!-- " +
	TimeString() + " -->");
    Page.Controls.Add(literal);
}
The current time (now)

It uses DateTime.Now. Here we see that the DateTime.Now class can be used to get the current time. On the Now property, we call ToString with a formatting parameter string. The string indicates that we want the date with the "short" hour (1-12, not 0-23), and the minutes and seconds. This method is static because it doesn't use any instance members on the class.

DateTime Format

Using Page_Load event. The above Page_Load event runs each time the page is run. This is important for adding the LiteralControl at the bottom of each page.

It adds a new LiteralControl. LiteralControl is simply a text string object that we can place quickly in the page. Look at how we use the constructor. We specify that we want an HTML comment. The TimeString() method is called. This returns the "2:26:42" style time string. We put it in the HTML comment. Finally, in the above code, we append the LiteralControl to the document. This is the object-oriented way of adding the comment to the end of the page.

Summary

The C# programming language

We looked at the LiteralControl class in the ASP.NET web framework and C# programming language. This is an object-oriented way of effectively adding timestamps to pages. You may also need to add timestamps to ASP.NET web controls, your HtmlTextWriter code, and other places.

asp:Literal Use ASP.NET Tutorials
.NET