9

How to add an additional css class from code behind using ASP.NET?

CURRENT TEXTBOX

<asp:TextBox ID="txt" CssClass="MyClass" runat="Server" />

DESIRED OUTPUT

<asp:TextBox ID="txt" CssClass="MyClass Error" runat="Server" />

Testing

txt.CssClass = "Error"

This replaces current css class.

txt.CssClass = "MyClass Error"

This works but but is greatly inefficient having to specify class.

txt.Attributes.Add("class", "Error")

This only works if no initial class is set.

txt.Attributes("class") += " Error"

This does not work for me.

8
  • txt.CssClass = txt.CssClass + " Error". Commented Aug 6, 2014 at 13:14
  • or perhaps txt.CssClass += " Error" would work Commented Aug 6, 2014 at 13:14
  • @mikey I also believe so, but am unable to test it right now. Commented Aug 6, 2014 at 13:15
  • @MelanciaUK yes same here ;) that is why I went with 'perhaps' Commented Aug 6, 2014 at 13:15
  • 1
    Give it to Rob W, the utility methods he's linked to are more robust. I imagine that one could become very frustrated dealing with the string concatenation and the helper methods help to prevent duplicates Commented Aug 6, 2014 at 13:20

2 Answers 2

14

Add additional CssClass like this:

txt.CssClass = txt.CssClass + " Error"

The above can also be abbraviated as:

txt.CssClass += " Error"
Sign up to request clarification or add additional context in comments.

Comments

3

I know that you were looking for a quick one-liner. However, this previous answer may prove useful going forward:

How to add more than 1 class to an element in ASP.NET?

Comments

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.