When should you use Page.DataBind() versus Control.DataBind()?
Page.DataBind
is Control.DataBind
. Neither the Page
class, nor the TemplateControl
class overrides Control.DataBind
.
Control.DataBind
does little more than call OnDataBinding
for the control, then it calls DataBind
for each child control.
For choosing between Page.DataBind()
versus Control.DataBind()
, here is the Microsoft guidance :
"Both methods work similarly. The main difference is that all data sources are bound to their server controls after the
Page.DataBind
method is called. No data is rendered to the control until you explicitly call either theDataBind
method of the Web server control or until you invoke the page-levelPage.DataBind
method. Typically,Page.DataBind
(orDataBind
) is called from thePage_Load
event."
There will be cases when you want specify control databinding individually, depending on the current page scenario. For a detailed level of control over which controls are bound and when controls are bound, I opt for the control-level DataBind()
methods.
In an ASP.NET page, you can bind directly to public/protected properties of your page's code-behind class. For example:
<form id="form1" runat="server"><%#HtmlUtility.HtmlEncode(MyProperty.ToString())%></form>
In this case, there is no specific control to call .DataBind() on - the page itself is the control. It just so happens that calling Page.DataBind() will also call DataBind() on all child controls, so if you're already doing a Page.DataBind(), there's no need to data bind the controls individually.