ASP.NET 2.0: Specifying an instance of an object for an ObjectDataSource

时光怂恿深爱的人放手 提交于 2019-12-22 11:17:59

问题


I'm using an ObjectDataSource to bind data to a GridView; it works fine except that it always creates a new object to use as a data source. I can do all the setup just fine but I cannot use an instance of an existing object to specify as the "data source" for it. Is it possible to do this? If so, how?

If it's not possible, why?

EDIT: Here's the gist of what's going on (object types changed): On the first page you are editting the attributes for a dog. One of the attributes is "has puppies" and if it's true, the next page you specify the names of those puppies. What's happening in my case is that those puppies are not getting linked to the original dog but to a "new" dog. (The implication that my problem is a "female dog" was coincidental. ;-) )


回答1:


Create an event handler for the ObjectCreating event on the ObjectDataSource.

You can assign the instance to using the ObjectDataSourceEventArgs property

protected void ObjectDataSource1_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
{
    e.ObjectInstance = myObject;
}

Wire this event up in the markup too

<asp:ObjectDataSource OnObjectCreating="ObjectDataSource1_ObjectCreating" />



回答2:


As I just discovered in my own question here, items stored in the Application Cache are going to pass themselves as a reference for use. You may consider storing your data there (or potentially in the Session as well) and pass items that way.



来源:https://stackoverflow.com/questions/398231/asp-net-2-0-specifying-an-instance-of-an-object-for-an-objectdatasource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!