0

I need to change a color in part of string. How to do this ?

if (kmTotalMil < allTotal || kmTotalMil > allTotal)
{
    return "You are " + kmTotalMil.ToString() + " km." + " in city " + allTotal.ToString() + " km.";
}

I need kmTotalMil.ToString() and allTotal.ToString() must be a RED color.

How to do this ?

Fermin
  • 34,961
  • 21
  • 83
  • 129
Gohyu
  • 468
  • 2
  • 10
  • 32
  • Strings don't have colors, they are just character arrays. Please explain how this string will be displayed. – CodeCaster May 11 '16 at 09:43
  • http://stackoverflow.com/questions/1178249/how-to-highlight-or-change-the-color-of-some-words-in-a-label-dynamically-at-run, http://stackoverflow.com/questions/31706385/how-to-change-the-colour-of-a-string-when-binding-to-a-label-in-asp-net – CodeCaster May 11 '16 at 09:47

2 Answers2

3

I'm assuming you're outputting this to html, in which case you'll need to use CSS to style your string. In the code below I'm returning a string which includes a HTML tag, span in this case, and I've added some inline styling with a css rule to change the color to red:

if (kmTotalMil < allTotal || kmTotalMil > allTotal)
{
    return "<span style='color:red'>some text</span>";
}

I would suggest you to go through some tutorials on CSS and string concatenation in C# as your next step.

Irshu
  • 8,248
  • 8
  • 53
  • 65
Phil
  • 3,568
  • 3
  • 34
  • 40
3

As you are asking this for asp.net sites you should use CSS to style the text:

if (kmTotalMil < allTotal || kmTotalMil > allTotal)
{
    return "You are <span style='color:red'>" + kmTotalMil.ToString() + "</span> km." + " in city <span style='color:red'>" + allTotal.ToString() + "</span> km.";
}

Here is the same result with string.Format:

if (kmTotalMil < allTotal || kmTotalMil > allTotal)
{
    return string.Format("You are <span style='color:red'>{0}</span> km. in city <span style='color:red'>{1}</span> km.", kmTotalMil, allTotal);
}
Marcel B
  • 508
  • 2
  • 9