1. Home
  2. Computing & Technology
  3. Delphi Programming

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

By , 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

Explore Delphi Programming
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. Delphi Programming
  4. Coding Delphi Applications
  5. Delphi Tips and Tricks
  6. 2005 Delphi Tips
  7. Fixing the ListBox (and DropDownList) ASP.NET Web Server control - adding Attributes to Items

©2009 About.com, a part of The New York Times Company.

All rights reserved.