I ran into an interesting issue with the new data binding model in ASP.NET 2.0 that I thought I'd document here.
The issue is with the implicit data-bind that occurs between controls like the GridView and their associated declarative data source (like the SqlDataSource). It is now up to the control to perform data binding at the right time, and your job is to just point it to the data source control it should use when it needs to bind data. The data binding itself usually occurs within the EnsureDataBound() method of the control, called within the CreateChildControls() virtual override. Now, if the control has ViewState enabled (which it will by default), the data it binds to in the initial GET request will be cached in ViewState on a subsequent post-back request. In fact, you have probably written code that looks something like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
myGrid.DataSource = GetDs();
myGrid.DataBind();
}
}
Knowing that the state is being restored from ViewState can save you an additional round-trip to your data store. The controls in ASP.NET 2.0 make this same optimization, so that they will not bother re-binding to the data source if the data is present in ViewState. Now this is usually what you want, but you should be aware of it since it can lead to surprising behavior. For example, if you have a button or other post-back generating control on a form alongside a GridView, and the effect of the button is to modify the underlying database (say it adds a new row to the table being displayed by the GridView), you won't see the changes made to the database when the page is rendered because the GridView is drawing its state from ViewState and not going back to the database. The solution, of course, is to disable ViewState on the GridView and force it to re-retrieve the data with each request.
Posted
Jul 20 2005, 01:20 AM
by
fritz-onion