Ahmad Farid
Ahmad Farid

Reputation: 14774

How to highlight or change the color of some words in a label dynamically at runtime?

I have a label containing some text and I want to highlight or change the color of some words in the text of the label and not all of the words. It has to be dynamic. Any suggestions?

It's for c# with ASP.NET in a user control in webpart in sharepoint

Upvotes: 6

Views: 34703

Answers (7)

Anastacio Ham
Anastacio Ham

Reputation: 21

I made a function to look up words in a text string and highlight them with color, the result is put into a label.

Function Remarcar(ByVal palabra As String, ByVal texto As String) As String

    Dim textoNuevo As String = String.Empty

    If Not String.IsNullOrEmpty(palabra) Then
        Dim split As String() = texto.Split(New Char() {" "c})

        For Each str As String In split
            If str.ToLower.Contains(palabra.ToLower) Then

                Dim a As String = String.Empty
                Dim b As Int32

                For i = 0 To str.Length
                    If str.ToLower.Substring(i, palabra.Length) = palabra.ToLower Then
                        a = str.Substring(i, palabra.Length)
                        b = i
                        Exit For
                    End If
                Next

                textoNuevo &= str & " "

                textoNuevo = textoNuevo.Replace(str.Substring(b, palabra.Length), "<span style=""background-color:Yellow;"">" & a & "</span>")
            Else
                textoNuevo &= str & " "
            End If
        Next
    Else
        textoNuevo = texto
    End If

    Return textoNuevo
End Function





        Dim texto As String = "I made a function to look up words in a text string and highlight them with color, the result is put into a label."

        Label1.Text = Remarcar("highlight", texto)

Upvotes: 2

Brian MacKay
Brian MacKay

Reputation: 32009

On the server-side, you could just embed some Html in your Label's text (VB):

myLabel.Text="Some normal text <span style='color: red;'>some red text</span>"

That's the basic mechanism, but 'dynamic' could mean a lot of things here. If you post some more details about exactly what you're doing, I might be able to help more.

One more thought: as Rob Allen pointed out, the Literal control may be a slightly better choice in this situation since it's intended to emit raw Html, whereas the Label wraps the text in a span so that the whole thing can be formatted easily.

Check this out for more details: StackOverflow: Literals versus Labels

For the record, depending on the situation I think a Label may actually be okay here.

Upvotes: 10

Greg
Greg

Reputation: 16690

You could use a Substitution control if caching is a concern.

<asp:Label ID="Label1" runat="server" Text="">
    <asp:Substitution ID="Substitution1" runat="server" MethodName="GetDynamicLabel"/>
</asp:Label>

protected static string GetDynamicLabel( HttpContext context )
{
    return string.Format( "<span style='background-color:Blue;'>{0}</span> {1}", "Blue", "Not Blue" );
}

Upvotes: 0

Russ Cam
Russ Cam

Reputation: 125538

For ASP.NET,

wrap the words you want highlighted in a <span>. Then set the <span> style background-color to the colour of your choice, or use a CSS class to do so.

For example,

<asp:Label runat="server">
    <span style="background-color:Blue;">Hello</span> World
</asp:Label>

or

<asp:Label runat="server" Text="<span style='background-color:Blue;'>Hello</span> World" />

EDIT:

If setting this in code behind, then you can do something like the following

 StringBuilder builder = new StringBuilder();
 builder.Append([start of text]);
 builder.Append("<span style=\"background-color:Blue;\">");
 builder.Append([text to highlight]);
 builder.Append("</span>");
 builder.Append([rest of text]);

 Label.Text = builder.ToString();

If you needed to match text already in the label against some specific text then something like the following

 string theTextToMatch = "[Text to match]";
 string theText = Label.Text;

 int leftIndex = theText.IndexOf(theTextToMatch, StringComparison.OrdinalIgnoreCase);
 int rightIndex = leftIndex + theTextToMatch.Trim().Length;

 StringBuilder builder = new StringBuilder();
 builder.Append(theText , 0, leftIndex);
 builder.Append("<span style=\"background-color:Blue;\">");
 builder.Append(theText, leftIndex, rightIndex - leftIndex);
 builder.Append("</span>");
 builder.Append(theText, rightIndex, theText.Length - rightIndex);

 Label.Text = builder.ToString();

Upvotes: 7

Denis Sadowski
Denis Sadowski

Reputation: 3133

Starting with:

<label> She sells sea shells by the sea shore </label>

We want "sells sea" to be red, and "the sea shore" to be highlighted.

<label> She <font color="red">sea shells</font> by <font style="BACKGROUND-COLOR: yellow">the sea shore</font></label>

All done!

Upvotes: 1

Matt Ball
Matt Ball

Reputation: 360046

You're going to need to be a lot more specific. What language is this in? Are you building an ASP.NET web site with C# code-behind? Is this label in a Windows Form? Please provide as much detail as you can, and update the tags on your post as well.

Upvotes: 1

kemiller2002
kemiller2002

Reputation: 115548

If it is asp.net (since you didn't specify) you are referring to you are going have to embed the words you want to highlight in another label.

    <asp:label runat="server" id="nonRed">some text 
        <asp:label runat="server" id="redText" style="color:Red">Red Text</asp:label>
   </asp:label>

Upvotes: 0

Related Questions