Nick
Nick

Reputation: 7525

Difference between control.Attributes.Add and control.Attributes[]

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?

Upvotes: 4

Views: 3064

Answers (2)

SwDevMan81
SwDevMan81

Reputation: 50018

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)

Upvotes: 4

Neil N
Neil N

Reputation: 25278

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

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

Upvotes: 0

Related Questions