by DRohm
9. August 2006 13:28
Using the ObjectDataSource and either a GridView or DetailsView you can very easily create data-driven web sites. What's even better about using these controls is that they give the developer a way to create data-driven pages without writing a single line of code. All of this is great and extremely useful, up until you need to do more customized solutions. For instance, what do you do if you need to dynamically set parameter values in the code-beside file for a GridView or DetailsView control?
You can do this by handling the appropriate event for the DataSourceControl. The events listed below all fire before their business class methods are called making them the perfect place to do your changes or updates.
- Selecting
- Inserting
- Updating
- Deleting
There are other events you can catch and handle, but for the purposes of what we want to do, these are the events of interest. Each of these events contain an InputParameters collection, passed in by the ObjectDataSourceMethodEventArgs parameter. Once inside the event, you can set the value of the parameter you need to modify and thats it. Here is an example of catching the Inserting event and setting the value of the "audit" parameter. In this case, the DetailsView is bound to a business class object. The InsertMethod for the DetailsView has an 'audit' parameter that we need to set dynamically when the event is fired:
protected void objCurrOption_Inserting(object sender, ObjectDataSourceMethodEventArgs e)
{
e.InputParameters["pollId"] = new IdentityField(e.InputParameters["pollId"].ToString());
e.InputParameters["audit"] = new Audit(CurrentUserName, CurrentUserIP, CurrentUser);
}
Again, this event is fired before the method on the business object is called. You can use the same method to dynamically set values for Updates, Deletes, and Selects.