In ASP.NET, you can bind controls individually (i.e. GridView1.DataBind()) or you can call Page.DataBind() to bind all controls on the page.
Is there any specific difference between the two calls? Are there times when one should be preferred over the other?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.
Method 2
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 thePage.DataBindmethod is
called. No data is rendered to the
control until you explicitly call
either theDataBindmethod of the Web
server control or until you invoke the
page-levelPage.DataBindmethod.
Typically,Page.DataBind(orDataBind)
is called from thePage_Loadevent.”
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.
Method 3
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.
Method 4
This is not a direct answer to subtilities between the two calls, but
about DataBind() vs Page.DataBind() I would like to share an interesting experience which may also really guide you to chose between both :
I just spent one complete day to figure why Ajax calls and events in a huge webapplication were broken (ItemCommand not raised on callbacks and postbacks, lost references, etc).
The reason was I had one ASCX which made a call to Page.DataBind() rather than DataBind() on itself.
It could seem obvious when you found it, but when you are dealing with weird behavior in a >500000 lines application and a lot of complexity in master/pages/controls, it’s not.
So beware of Page.DataBind() if you call it at the wrong place !
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0