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.