Thursday, February 10, 2011

Applying html formating in label control

The html formating is applied great in this case. The Surname is displayed with size 5.

lblWelcome.Text = "Welcome:<font size=''5''>" & txtSurname.Text & "</font>"

Why the html style is not applied in this example?

lblWelcome.Text = "Welcome:<font color=''white''>" & txtSurname.Text & "</font>"
  • You could just set the ForeColor property on the Label.

    lblWelcome.Text = txtSurname.Text;
    lblWelcome.ForeColor = "white";
    

    You'd have to put the 'Welcome' outside the label, but it would probably make more logical sense.

    Welcome:<asp:Label id="lblWelcome" runat="server" />
    
    womp : Even though it doesn't directly answer the question, this is +1 simply because outputting font tags is really 1996...
    g . : @womp - sometimes the answer is there is a better way. :-)
    From g .
  • Hi there.

    As an alternative, you could use the ASP.NET Literal web control and set its Mode property to Encode or Transform.

    Literal1.Mode = LiteralMode.Encode
    
    Literal.Text = "Welcome:<font color='white'>" & txtSurname.Text & "</font>"
    

    In the above code, the HTML elements will be transformed into proper HTML, leaving just the surname text in white.

    Cheers. Jas.

    Chocol8 : I have tried Encode, Transform and PassThrough but it didn't work out. +1 for the literal control :)
  • Please, please, please don't use font tags. Also, if you really want to output HTML from the server side then you should be using a Literal control.

    Here is an example of how I would do it:

    aspx/ascx file:

    Welcome: <asp:Literal id="lit1" runat="server" />
    

    code behind:

    lit1.Text = "<span class='welcome'>" & txtSurname.Text & "</span>"
    

    OR your other example:

    lit1.Text = "<span class='welcomeBig'>" & txtSurname.Text & "</span>"
    

    css:

    span.welcome { color:#fff; }
    span.welcomeBig { font-size:24px; }
    

    Hope this helps

    Chocol8 : I guess CSS overides everything! I got the desired style without even using the literal control
    From Darko Z
  • Also don't forget to HTML encode the surname: Server.HtmlEncode(txtSurname.Text);

    From Dan Diplo

0 comments:

Post a Comment