How to Use Label Web Controls in ASP.NET

How to Use Label Web Controls in ASP.NET
Page content

The Literal control does not allow for enhancement. It is a What You See Is What You Get control. When a server renders a Web page, the HTML contents of a Literal control display exactly as created. However, the Label Web Control has a number of ways to format the display and can spruce up your pages, even changing the display to match existing conditions, such as the time of day.

Adding Text Display Controls

To see the difference and learn to use the ASP.NET Labe Web Control, use Microsoft Visual Web Developer 2008 Express Edition to open a web page. Click on “File, “New File” in an existing Website on your computer. Select the “Web form” template. Double-click on the Literal control to add it to the page and do the same with the “Label” control. Double-click on the “Button” control to place a command button on the form and drag it down below the label. Then click on the new command button and change the Text property to “Submit." Click on the Literal control. Scan down the list of values you can modify in the “Properties” pane on the right of the screen. You will see only four choices: Enable State, Mode, Transform, and Visible. Now compare this to the Label control by viewing its properties. Any property with a plus (+) sign next to it indicates there are sub-properties as well. While you are looking, change the “Text” property to read “Property Demonstration.”

ASP.NET Label Control Properties

When you expand the sub-categories under “Font,” you will see that you can vary many attributes, including the font name, whether it appears in bold or italic and the size. Other property values you can fiddle with include the text size, the backcolor, forecolor, border color, style, and width, and whether the label is visible or not. The image shows a few of these control properties.

Coding Possibilities with Label Controls

With a little code, you can control the appearance of the label depending on user input. For example, on a login screen, you would want to be able to warn the user if the user name was blank. However, there is nothing gained by displaying this error message from the start. A couple of lines of “IF” “THEN” code to test for the proper input could change the “Visible’ property of the Web Label from True to False. A very simplified example of code would be:

If TextBox1.Text = “” then Label1.Visible=True. Changes that are more complicated are possible at run time on a Web server. Depending on user input, you might want to change a label’s color or size to dramatize some event.

Besides the simple examples in this ASP.NET tutorial, there are multiple possibilities to explore. For example, a somewhat trivial example might be to display a calendar. If the current date matches a pre-selected one, for example your birthday, change the label caption to read “Happy Birthday!”

.