tags:

views:

639

answers:

1

We have a couple of ASP.Net dataview column templates that are dynamically added to the dataview depending on columns selected by users.

These templated cells need to handle custom databindings:

public class CustomColumnTemplate: 
    ITemplate
{
    public void InstantiateIn( Control container )
    {
        //create a new label
        Label contentLabel = new Label();

        //add a custom data binding
        contentLabel.DataBinding +=
            ( sender, e ) =>
            {
                //do custom stuff at databind time
                contentLabel.Text = //bound content
            };

        //add the label to the cell
        container.Controls.Add( contentLabel );
    }
}

...

myGridView.Columns.Add( new TemplateField
    {
       ItemTemplate = new CustomColumnTemplate(),
       HeaderText = "Custom column"
    } );

Firstly this seems rather messy, but there is also a resource issue. The Label is generated, and can't be disposed in the InstantiateIn because then it wouldn't be there to databind.

Is there a better pattern for these controls?

Is there a way to make sure that the label is disposed after the databind and render?

+1  A: 

I have worked extensively with templated control and I have not found a better solution.

Why are you referencing the contentLable in the event handler?

The sender is the label you can cast it to the label and have the reference to the label. Like below.

        //add a custom data binding
        contentLabel.DataBinding +=
            (object sender, EventArgs e ) =>
            {
                //do custom stuff at databind time
                ((Label)sender).Text = //bound content
            };

Then you should be able to dispose of the label reference in InstantiateIn.

Please note I have not tested this.

David Basarab