1

How do I stick HTML formatting into a String object in C#?

Here's what I have:

c.DepartmentAbbr.ToString() + " - (" + c.DepartmentName.ToString() + ")"

where c.DepartmentAbbr.ToString() and c.DepartmentName.ToString() are both fields being selected from a data context using LINQ.

Here's what I essentially want:

"<b>" + c.DepartmentAbbr.ToString() + "</b> - (" + c.DepartmentName.ToString() + ")"

so that the first word shows up in bold. The above just shows the literal text with the bold tags and everything. I assume I will need to use String.Format but I can't quite find a good example that helps me know how to use it to do what I want.

Update

Here are a few more details that I didn't think were important but I think by now they must be.

Here is the control I'm using. ASPX code:

 <telerik:RadComboBox ID="rcbDepartments" runat="server" AppendDataBoundItems="True"
        AutoPostBack="true" NoWrap="true" Width="250px">
        <Items>
            <telerik:RadComboBoxItem Text="All Departments" Value="-1" />
        </Items>
    </telerik:RadComboBox>

And I'm adding items to this control using LINQ in C#:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        var abbr = from c in DB.Departments
                   where c.DepartmentAbbr != "BInst"
                   select c;

        foreach (var c in abbr)
        {
            String s = String.Format("{0} - ({1})", c.DepartmentAbbr, c.DepartmentName);
            rcbDepartments.Items.Add(new RadComboBoxItem(s, c.DepartmentID.ToString()));
        }
    }
}

The RadComboBoxItem object accepts either (), (String text), or (String text, String value), and I am using the latter.

1
  • Please show the ASP.NET control you are setting this to on the aspx page and the full code behind code. Like: <asp:TextBox runat="server" id="txtbox"></asp:TextBox> txtbox.Text = "my html string"; Commented Dec 23, 2009 at 4:20

7 Answers 7

9
String.Format("<b>{0}</b> - ({1})", c.DepartmentAbbr, c.DepartmentName)

Here is a great reference to string formatting in C#:

http://blog.stevex.net/string-formatting-in-csharp/

Sign up to request clarification or add additional context in comments.

1 Comment

I actually found that one while doing some research. It is a great reference indeed but doesn't answer my question.
4

For anyone trying to do this in ASP.NET MVC...

This doesn't work:

<%=String.Format(resourceString, "<b>" & Model.UserName & "</b>")%>

The bold tags are HTML encoded, as you'd expect.

However, this works a treat:

<%=String.Format(resourceString, MvcHtmlString.Create("<b>" & Model.UserName & "</b>")%>

Comments

2
MvcHtmlString s = MvcHtmlString.Create(String.Format("{0} - ({1})", c.DepartmentAbbr, c.DepartmentName));

I think you better change the String s to MvcHtmlString object.

1 Comment

Thanks for the response but this question was not related to MVC.
2

I guess you are looking for a way to have the object c to spit out a HTML formatted string.

Take this as an example:

public class myExample : IFormattable{
   private string myExampleStr;
   public myExample(string sampleStr){
      this.myExampleStr = sampleStr;
   }

   /* Implement an Equals() function - OVERRIDE! */
   public override bool Equal(object obj){
      return true;
   }

   /* Implement an ToString() function - OVERRIDE */
   public override string ToString(){
      return this.myExampleStr;
   }

   /* Implement an GetHashCode() function - OVERRIDE */
   public override int GetHashCode(){
      return this.myExampleStr.GetHashCode();
   }

   /* Here we implement the IFormattable interface */
   public string ToString(string format) {
      return this.ToString(format, null);
   }
  
   public string ToString(IFormatProvider formatProvider) {
      return this.ToString(null, formatProvider);
   }

   public string ToString(string format, IFormatProvider formatProvider) {
      if (string.IsNullOrEmpty(format)) format = "G";
      if (formatProvider != null) {
         ICustomFormatter formatter = formatProvider.GetFormat(this.GetType()) as ICustomFormatter;
         if (formatter != null)
            return formatter.Format(format, this, formatProvider);
      }
      switch (format) {
         case "b": return string.Format("<b>{0}</b>", this.myExampleStr);
         case "i": return string.Format("<i>{0}</i>", this.myExampleStr);
         default: return this.myExampleStr;
      }
   }
}

And suppose we instantiated this class like this:

myExample example = new myExample("tomb");

And issue a simple ToString() call on the object to print out a HTML tag for bold as shown below

Console.WriteLine("{0}", example.ToString("b"));
// Output would be <b>tomb</b>

This example serves to illustrate how to use a custom parameter to the ToString() method so that you can use bold or italic HTML tags embedded, or any other way of formatting a value based on the parameter used for the ToString function of this class.

Does this answer your question?

1 Comment

I appreciate the answer but this seems to be just a bit more complicated way of doing what I've already tried using the String.Format method. The problem is that I'm using a RadComboBox control to add these to and I'm pretty sure by now that this control doesn't allow me to do HTML formatting on the objects as I enter them. the only option I have is to use an Item Template which I can not do in this case because of an entirely different problem I was already dealing with which caused me to switch to my current method.
0

I think the problem is somewhere else. Are you putting this string in a Label control or a Literal control? If it's a Label, I believe it's escaping the text for you. Put it in an asp:Literal control instead. And btw, you don't need to call .ToString() so much. You can just use:

"<b>" + c.DepartmentAbbr + "</b> - (" + c.DepartmentName + ")"

and ToString() will essentially be called for you.

3 Comments

Did you try using asp:Literal or tried removing ToString() methods?
I tried removing the ToString() methods. I can't use an asp:Literal because I am already within a combobox control.
That's your real problem then. You can not do what you are attempting inside a combo box. You will have to use another control entirely.
0

As I've researched more and more I've pretty much come to the conclusion that what I want to do is not possible. I'm using a RadComboBox to stick the items into, but I'm having to do some funcky stuff with LINQ on the server side such that I have to stick the items into the combo box using the Items.Add method which only accepts System.String. Thank you all for your help and comments but I think I'm just going to have to make do with what I have in this case.

Here are a few more details that I didn't think were important but I think by now they must be.

Here is the control I'm using. ASPX code:

And I'm adding items to this control using LINQ in C#: protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { var abbr = from c in DB.Departments where c.DepartmentAbbr != "BInst" select c;

        foreach (var c in abbr)
        {
            String s = String.Format("{0} - ({1})", c.DepartmentAbbr, c.DepartmentName);
            rcbDepartments.Items.Add(new RadComboBoxItem(s, c.DepartmentID.ToString()));
        }
    }
}

The RadComboBoxItem object accepts either (), (String text), or (String text, String value), and I am using the latter. I am pretty sure by now that due to the restrictions on the RadComboBoxItem only accepting Strings that I can not do HTML formatting on the items without using the Item Template tags in ASPX. Unfortunately for my situation I can not do this because that was already causing some other problems for me which I why I'm doing what I am currently trying to do.

Comments

-1

If you're outputting this on a webpage - try using the:

Server.HtmlEncode(string)
Server.HtmlDecode(string)

methods.

2 Comments

I actually just tried this. Unfortunately, all this really seems to do is change the '<' and '>' character to their entities "&lt;" and &gt;" and then displaying the string with these all showing.
This is dangerous advice. String.Format handles HTML escaping, which helps protect against xss (cross site scripting). If you're using String.Format, then you probably have a string that you trust that containing HTML, and a variable from the user that shouldn't contain HTML. String.Format makes sure that variable gets escaped, HtmlEncode/Decode on the whole string doesn't.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.