Tuesday, July 08, 2008

ItemTemplate when in WebControl or WebPart

I have been working on a project to build webparts for MOSS and some of them are using Repeater controls.

Well when using repeaters in normal life, like in ASPX or ASCX pages, you define the ItemTemplate and other template parts directly in the ASPX or ASCX, but when you are creating Web Part or Web Control, then you have to do more or less everything in CreateChildControls.

Well I have tried for the Repeater to use custom class that implements ITemplate and then add attach this one to the Repeater.ItemTemplate, well this work at first, but then I had the next situation, I needed something like this:

<asp:Repeater onItemDataBound="">
<ItemTemplate>
<asp:LinkButton onCommand="btnOnCommand" ID="btn"/>
</ItemTemplate>
</asp:Repeater>

Then get the button object in ItemDataBound, attach something in the CommandArgument. Then handle the click. Well this did not work well when I had the separate class for the ItemTemplate.

I had to come with better solution, well what I did, was I created one website project with VS and precompiled it so that it is not updateable. Then used the one of the greatest tools for .NET development Reflector.NET and disassembled the compiled code.

Here it is what I have found, how it is done and how it should be done:



repeater.ItemTemplate = new CompiledTemplateBuilder(
new BuildTemplateMethod(this.bulildItemTemplate));

private void buildItemTemplate(Control __ctrl)
{
IParserAccessor accessor = __ctrl;
LinkButton button = this.buildButton();
accessor.AddParsedSubObject(button);
}
private LinkButton buildButton()
{
LinkButton button = new LinkButton();
button.TemplateControl = this;
button.ApplyStyleSheetSkin(this);
button.ID = "btn";
button.Text = "text";
button.Click += new EventHandler(this.btn_click);
return button;
}

I have found the CompiledTemplateBuilder extremely useful class this was really great solution.

Labels: , , ,

0 Comments:

Post a Comment

<< Home