views:

283

answers:

1

I was wondering about some best practices for data binding in web forms.

For example we have a control:

public partial class MyUserControl : UserControl
{
    public override void DataBind()
    {
        //#1
        base.DataBind();
        //#2
    }
}

If we wanted that control to bind its data automatically we would do something like this:

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        this.DataBind();
    }
}

In the first section of code if we do our data binding before the call to base.DataBind() (#1) then that means that, if for example we databind a ListView, we don't have to call ListView.DataBind() because when we call base.DataBind() on our control it recursively calls DataBind on all child controls. Also, we won't have access to any of the properties of the control that were assigned to it using the data binding code blocks <%# %>

If we do our binding on our controls after base.DataBind() (#2) then this means that DataBind is called on these controls twice. Once when base.DataBind() is called, and the second time when we are forced to call control.DataBind().

Does anyone know of some sort of pattern I can follow here that I don't know about?

Am I making any sense here?

What am I doing wrong?

EDIT: Looking at this page: http://msdn.microsoft.com/en-us/library/w5e5992d.aspx

Use this method to bind data from a source to a server control. This method is commonly used after retrieving a data set through a database query. The method is primarily used by control developers; most controls perform data binding automatically.

It appears that best practice is to bind controls data automatically. Databinding is for when we explicitly set a data source.

A: 

I've encountered problems previously, when pages become complex and you are relying on user controls binding their own data in the page load event. This has resulted in some long debugging sessions, as you can't be guaranteed exactly when this page load event in the control will fire.

Now, that said, these pages weren't too well designed, and we shouldn't have run into this problem, but I prefer to stick with the explicit and have my page tell the child controls when to do their thing - you may wish to avoid calling base.DataBind and do it explicitly instead - you may also wish to not override the DataBind method in this way and instead call the method on your control by another name.

Paddy
I agree with naming data binding methods something other than DataBind, though I normally call these methods inside the DataBind method! Perhaps not a great idea.
AndrewVos