21

I am setting 2 css class in the code behind in ASP.NET

I could either do:

txtBox.Attributes.Add("class", "myClass1");
txtBox.Attributes.Add("class", "myClass2");

it's always apply one Class .. How can i add thw two classes ?

4 Answers 4

40

The Add method is actually a Put, since it replaces the value behing the key "class". In HTML/css you can have several classes by separating with a space.

txtBox.Attributes.Add("class", "myClass1 myClass2");
Sign up to request clarification or add additional context in comments.

2 Comments

Actually it is better to set class directly to CssClass attribute: txtBox.CssClass = "myClass1 myClass2". In this way you can also add/remove classes later: txtBox.CssClass += " myClass3" / txtBox.CssClass.Replace("myClass1", "")
This is what I needed, Marc and @Grengas. I would have done this straight away but was looking for a more normalized interface to the CSS class than twiddling a flat string. Par for the course, I guess.
8

try

txtBox.Attributes.Add("class", "myClass1 myClass2");

I think this will work.

Comments

2

You can also try

txtBox.CssClass = "myClass1 myClass2";

2 Comments

Not helpful because this will replace existing classes
Worked for me since I needed multiple classes during control creation.
1

try

txtBox.Attributes.Add("class", "my_Class1 my_Class2");

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.