Whenever you try to add any attribute to any listitem at runtime using
ListItem.Attributes.Add("onclick","alert('I m a listitem')")It does add the attribute to the listitem but never really renders the same.
Eg - In case you add an attribute to the listitem above, when you check the page source, you will see something like this:
< option onclick="alert('i m a listitem')" > ListItem </option >So the attribute has been added but when you click on this listitem, the alert will never come up.
Why Attributes Cannot Be Applied to ListItems of a List Control
Unfortunately none of the list controls render their items' attributes. This is clearly a known bug, as there are plenty of discussions on this topic on the newsgroups. If you use Reflector to poke around the source code of the list controls you'll find that they simply omit any sort of writing of the Attributes. Part of this is probably due to the fact that the
ListItem
class, which is the class that represents each instance of a list control prior to being rendered. The Attributes
collection is defined in the
System.Web.UI.WebControls.WebControl
class and automatically is persisted to view state, so that it's values persist across postbacks. Part of the problem lies in that the ListItem
class does not derive from WebControl
. Furthermore, while it does have an Attributes
property, the values are NOT persisted to view state.More On This And a possible Solution to this BUG on 4GuysFromRolla
BTW : - I am almost done with my CodeConvertor utility and will post the same as soon as it is complete.
-- Ashutosh
PS- Hah it took me quite some time to put the line
< option onclick="alert('i m a listitem')" > ListItem </option >
the way it looks now as the site blocks all HTML tags....;-)