DataBind and Postback
Asked Answered
S

3

6

This is a general how does DataBind work questions...

I have a simple page with a GridView that is bound (in the aspx code) to an ObjectDataSource.

I can look in the Select() function called by the ObjectDataSource to see that it is called on the initial load and on every post back. I have some logic that happens on post backs that will affect the GridView's data, and I want to call GridView.DataBind() later on in the post back, after I've made some changes.

Is there a way to prevent the automatic rebinding that happens on each post back? Does this mean I can't use an ObjectDataSource for this control?

Sanitarian answered 6/5, 2009 at 19:9 Comment(0)
E
12

You're correct in that the fine grained control you're looking for is not possible and requires the code behind. ASP.NET's data source objects are nothing but a pain in the a**. You'll find that as you use them you'll get situations like this cropping up again and again.

Some of the problems you'll find are:

  • Not strongly typed
  • Inflexible (as you've noted)
  • Muddy up the presentation code

I've taken to doing all data access in the code behind and haven't looked back.

Eta answered 6/5, 2009 at 19:17 Comment(0)
W
9

I fought with this automatic binding as well and thought I post my solution here:

  1. remove the "DataSourceID" from the ASPX page, when its not set, there is no automatic binding
  2. set the DataSourceID in the CodeBehind only when DataBinding is needed: myGridView.DataSourceID = "MyDataSource";
  3. do not call myGridView.DataBind() explicitly, databinding happens automatically at PreRender

Took me a while to figure this out, but now wverything works fine.

Context

I use the ObjectDatasource because it handels all the paging and sorting of the Gridview automatically for me. I am using a data layer with Linq2SQL and use its Skip() and Take() methods to load only the amount of data needed to populate one page of the GridView.

Using the SelectMethod and SelectCountMethod of the ObjectDataSource

Whittington answered 10/6, 2010 at 14:48 Comment(1)
Thanks for the suggestion. I've gone with Gavin's suggestion of just avoiding the mess. My company has since switched to Telerik which supports a really clean code-behind binding method called "NeedDataSource". Still, if I need to switch back, I'll give this a try.Sanitarian
T
2

Yes. If you want that kind of control over when the databinding happens you need to do it in the code behind.

Tantalize answered 6/5, 2009 at 19:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.