Thursday, 12 January 2012

What is the difference between a Label and Literal control in asp.net ?

Both the Label and Literal controls allow you to specify some text which appears
on a web page. The main difference between them is "Label" control display the
text wrapped around in a span tag. literal control doesn't do anything like that.
It just display a text without wrapping it with anything.
For example:-
Suppose you have a label and a literal control in your aspx page :-

<asp:Label ID="label1" runat="server"></asp:Label>
<br />
<asp:Literal ID="literal1" runat="server"></asp:Literal>

Now, bind your controls with some text :-

label1.Text = "label text";
literal1.Text = "literal text";

When you execute the code, you will see this:-

<span id="label1">Hello This is label text</span>
<br />
Hello This is literal text

In the above output, we see that the label text is wrapped around a span tag and
the literal text is simply putting a text in it.
Note: If you do not need styling then its better to use literal. But do remember,
label control has much more properties than the literal control, so choose wisely.

No comments:

Post a Comment