I've been asked many times:
"How can I add an onclick client-side event to each ListItem in a
CheckBoxList? I tried adding an onclick attribute to the first check box:
MyCheckBoxList.Items[0].Attributes.Add('onclick', 'alert("first checkbox clicked!")') ;
Though the attributes get added they are not rendered to the page?!"
CheckBoxListItemAttributes Web Control
Here's the fixed CheckBoxList, the one that actually renders its items attributes (by overriding the Render method and making sure each Item attributes are rendered):
~~~~~~~~~~~~~~~~~~~~~~~~~
unit CheckBoxListItemAttributesUnit;
interface
uses System.Text, System.Web.UI, System.Web.UI.WebControls, System.IO;
type
CheckBoxListItemAttributes = class(CheckBoxList)
strict protected
procedure Render(writer: HtmlTextWriter) ; override;
end;
implementation
{ CheckBoxListItemAttributes }
procedure CheckBoxListItemAttributes.Render(writer: HtmlTextWriter) ;
var
strAttributes: string;
idx: Integer;
index: Integer;
endIndex: Integer;
liHtmlTW: HtmlTextWriter;
liSW: StringWriter;
liSB: StringBuilder;
myHTML: string;
htmlTW: HtmlTextWriter;
SW: StringWriter;
SB: StringBuilder;
begin
SB := StringBuilder.Create;
SW := StringWriter.Create(SB) ;
htmlTW := HtmlTextWriter.Create(SW) ;
inherited Render(htmlTW) ;
myHTML := SB.ToString;
liSB := StringBuilder.Create;
liSW := StringWriter.Create(liSB) ;
liHtmlTW := HtmlTextWriter.Create(liSW) ;
index := 0;
idx := 0;
while (idx < Items.Count) do
begin
if (Items[idx].Attributes['Visible'] = 'False') then
begin
index := myHTML.IndexOf('<tr>', index) ;
endIndex := (myHTML.IndexOf('</tr>', index) + '</tr>'.Length) ;
myHTML := myHTML.Remove(index, (endIndex - index)) ;
end
else
begin
index := (myHTML.IndexOf('<input ', index) + '<input '.Length) ;
liSB.Remove(0, liSB.Length) ;
Items[idx].Attributes.Render(liHtmlTW) ;
strAttributes := (liSB.ToString + ' ') ;
myHTML := myHTML.Insert(index, strAttributes) ;
end;
idx := idx + 1;
end;
writer.Write(myHTML) ;
end;//Render
end.
~~~~~~~~~~~~~~~~~~~~~~~~~
Delphi tips navigator:
» Fixing the ListBox (DropDownList) ASP.NET control - rendering Item Attributes
« How to (bulk) import data from an ASCII (.txt) file into a DB using ADO and only one INSERT statement

