Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 635
DreamTeK Avatar asked Aug 06 '14 13:08

DreamTeK


2 Answers

Add additional CssClass like this:

txt.CssClass = txt.CssClass + " Error"

The above can also be abbraviated as:

txt.CssClass += " Error"
like image 188
DreamTeK Avatar answered Nov 17 '22 03:11

DreamTeK


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?

like image 3
Rob W. Avatar answered Nov 17 '22 05:11

Rob W.