views:

199

answers:

5

Hello,

I have a data access layer, a business logic layer and a presentation layer (ie. the pages themselves).

I handle the OnPreInit event and populate collections required for the page. All the data comes from an SQL server database and I do not use caching.

I handle a button click event to grab values from a form and insert a new object into the database. The problem is that by the time I handle the click event, the collections have already been populated, so the new item which has been inserted into the database has not been retrieved.

What is the accepted solution to this?

I could insert the new object directly into the collection and re-bind the GridView, but the SQL query selects only a set of objects and the new object could fall outside of this set.

Thanks!

+1  A: 

Perform your data binding operations later in the page lifecycle, e.g. in the page PreRender event which fires after any control events have been handled.

pmarflee
A: 

You should just handle the click event. Then after your database update/insert, you must rebind your data. Depending upon your implementation, you might need to re-post the page. If you were to use normal data binding you could just call the bind method again.

Jennifer Zouak
I want to avoid another round trip to the database and the web server if possible, it seems unnecessary in this situation.
Phillykins
If the business logic is in the database, you have to ask the database what to do. You could return some value from the insert statement that told you what to do, but that seems hackish.
Greg
A: 
  1. Retrieve data on the Page.LoadComplete event and do a data bind.
  2. If for some reason, should retrieve them only on PreInit, then retrieve them on for !IsPostBack condition and bind them and for PostBack conditions, handle them on LoadComplete
Ramesh
+2  A: 

I generally do databinding in two places in my pages:

  1. Inside Page_Load, if !IsPostBack to load the initial state.

  2. As one of the last lines in event handlers to show the result of adding/editing/deleting a record.

The issue you're running into is just the result of using OnPreInit to do data binding, so you're probably going to have to stop doing that, or try one of the sub-optimal approaches that others have suggested (redirecting back to the page after a postback).

Cory Grimster
Cory's explanation is the most complete. The key here is that you don't want to rebind your data on PostBack, unless it is explicitly required because of a user action (ie, adding a new item). Look at any of Microsoft's Databinding examples, like for the GridView.
Bryan
This is great, along with the tip from pmarflee I've solved the problem. Thanks!
Phillykins
A: 

You could use this method to determine which control issued the postback in the PreInit: http://blogs.microsoft.co.il/blogs/gilf/archive/2010/03/01/discover-which-control-raised-a-postback.aspx

Greg