ASP.NET: Bold parts of text using HtmlGenericControl

2.9k views Asked by At

I am a complete ASP.NET newbie, so this will probably be simple.

I have a label which text is set dynamically in the code behind using the following pseudo code

label.Text = string.Format(SOME-DYNAMIC-MESSAGE(ID,1), name, day);

The SOME-DYNAMIC-MESSAGE has a form of, where {0} and {1} refers to variables name and day.

Hello {0}, today is {1}.

I need to make those variables bold. I am trying to wrap them in span, so I can access them from CSS using this code

HtmlGenericControl bold = new HtmlGenericControl("span");
    bold.InnerText = name;
    bold.Attributes.Add("class", "bold");

label.Text = string.Format(SOME-DYNAMIC-MESSAGE(ID,1), bold, day);

but it doesn't work, no extra wrapper added. It even stopped to show me the the content of the variable.

Anybody knows how to fix this?

2

There are 2 answers

0
Zaki On BEST ANSWER

Try :

label.Text = string.Format(SOME-DYNAMIC-MESSAGE(ID,1), "<span style=\"font-weight:bold\">" + bold + "</span>", "<span style=\"font-weight:bold\">" + day + "</span>");
1
Glenn Ferrie On

Here is a quick sample app (Console app) to demonstrate an approach. I think you are trying to format the input string for String.Format and make the font-weight of the token ({0}, {1}, etc...) bold.

use this Func<string,string> to format the input string. then add the following CSS to your html page:

class Program
{
    static void Main(string[] args)
    {
        var input = @"Hello {0}, today is {1}.";

        Func<string, string> SomeDynamicMessage = s => {
            var val = s;
            val = val.Replace("{", "<span class='bold-token'>{");
            val = val.Replace("}", "}</span>");
            return val;
        };

        Console.WriteLine(SomeDynamicMessage(input));

        // output: Hello <span class='bold-token'>{0}</span>, today is <span class='bold-token'>{1}</span>.
        var final = Console.ReadLine();
    }
}

Css snippet:

.bold-token { font-weight: bold; }

Final output:

Hello <span class='bold-token'>{0}</span>, today is <span class='bold-token'>{1}</span>

EDIT -- MORE INFO

Here is how you should use it:

var input = @"Hello {0}, today is {1}.";
label.Text = string.Format(SomeDynamicMessage(input), "test", "Thursday");

and the output would be:

Hello <span class='bold-token'>test</span>, today is <span class='bold-token'>Thursday</span>