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
On the server-side, you could just embed some Html in your Label's text (VB):
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.
Starting with:
We want "sells sea" to be red, and "the sea shore" to be highlighted.
All done!
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.
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.
For ASP.NET,
wrap the words you want highlighted in a
<span>
. Then set the<span>
stylebackground-color
to the colour of your choice, or use a CSS class to do so.For example,
or
EDIT:
If setting this in code behind, then you can do something like the following
If you needed to match text already in the label against some specific text then something like the following
I made a function to look up words in a text string and highlight them with color, the result is put into a label.