1. Computing

Fixing the ListBox (DropDownList) ASP.NET control - rendering Item Attributes

ListBoxItemAttributes Web Control

From , former About.com Guide

When you use the ListBox (or the DropDownList) Web Server ASP.NET control, if you try to add custom attributes to an Item, the key-value pairs are not rendered to the result page. Here's how to fix this behavior.

I've been asked many times:
"How can I add an onclick client-side event to each ListItem in a ListBox? I tried adding an onclick attribute to the first check box:

MyListBox.Items[0].Attributes.Add('onclick', 'alert("first item clicked!")') ;

Though the attributes get added they are not rendered to the page?!"

ListBoxItemAttributes Web Control

Here's the fixed ListBox, the one that actually renders its items attributes (by overriding the RenderContents method and making sure each Item attributes are rendered).

Note: the same approach can be used to "fix" the DropDownList ASP.NET control.

~~~~~~~~~~~~~~~~~~~~~~~~~
unit ListBoxItemAttributesUnit ;

interface

uses
   System.Web.UI,
   System.Web.UI.WebControls,
   System.Collections;

type
   ListBoxItemAttributes = class(ListBox)
   strict protected
     procedure RenderContents(writer: System.Web.UI.HtmlTextWriter) ; reintroduce;
   end;

implementation

procedure ListBoxItemAttributes.RenderContents(writer: System.Web.UI.HtmlTextWriter) ;
var
   enumerator: IEnumerator;
   li: ListItem;
begin
   enumerator := Self.Items.GetEnumerator;
   while enumerator.MoveNext do
   begin
     li := ListItem(enumerator.Current) ;
     writer.WriteBeginTag('option') ;
     writer.WriteAttribute('value', li.Value) ;
     if (li.Selected = True) then
       writer.WriteAttribute('selected', '1') ;
     li.Attributes.Render(writer) ;
     writer.Write(System.Web.UI.HtmlTextWriter.TagRightChar) ;
     writer.Write(li.Text) ;
     writer.WriteEndTag('option') ;
     writer.WriteLine;
   end;
end; //RenderContents

end.
~~~~~~~~~~~~~~~~~~~~~~~~~

Delphi tips navigator:
» How to cancel the TDBNavigator button click
« Fixing the CheckBoxList ASP.NET Web Server control - adding Attributes to Items

©2013 About.com. All rights reserved.