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

 Posted by Akiii on 10/24/2011 | Category: ASP.NET Interview questions | Views: 17589 | Points: 40
Answer:

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. On the contrary, 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">label text</span>

<br />
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.

Please, note that 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.

I hope i have made myself clear. Any problem or error with the above, please let me know.

Thanks and Regards
Akiii


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Posted by: Laghaterohan on: 10/24/2011 | Points: 10
Nice. However can you elaborate some instances wherein we should use Literal control instead of Label as a good programming practice?


Posted by: Akiii on: 10/25/2011 | Points: 10
Hi Rohan,
Thanks for ur feedback. I have already stated that in the article. Please refer to the line below :-

Please, note that 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.

Thanks and Regards
Akiii

Login to post response