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
