tags:

views:

214

answers:

2

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

I could either do:

txtBox.Attributes.Add("class", "myClass");

or

txtBox.Attributes["class"] = "myClass";
  1. What are the differences?
  2. Are there any situations in which one should be used over the other?
  3. What happens in case 1 if the class is assigned in the aspx page already? Does it overwrite it?
A: 

One is adding an attribute, the other is referencing/setting it.

You may not want to add it if it already exists.

Neil N
+1  A: 

1) Add adds the attribute, while [] allows you to access the value directly and assign it
2) Use [] if Attributes.Contains the value, otherwise Add it
3) Usually an ArgumentException will occur (An item with the same key has already been added)

SwDevMan81