How To: Access Underlying Data of the ObjectDataSource

A gentleman in my ASP.NET 2.0 class a while ago asked me how to access the underlying object used for the ObjectDataSource control.  Suppose you have some code in App_Code like so:

public class DataManager
{
    
public DataSet SelectDataSet()
    {
        
// code that populates the dataset...
        
DataSet ds GetPopulatedDataSet();
        return 
ds;
    
}
    
// supporting methods here...
}

Now on the .aspx page we have an ObjectDataSource control as follows:

<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" 
    TypeName
="DataManager"
    SelectMethod
="SelectDataSet"
    OnSelected
="ObjectDataSource1_Selected">
</asp:ObjectDataSource>

Notice the OnSelected attribute points to a method called ObjectDataSource1_Selected. This is the event where we can get access to the underlying data object. Here is the code for the event handler:

protected void ObjectDataSource1_Selected
    (
object sender, ObjectDataSourceStatusEventArgs e)
        {
          DataSet underlyingDataSet 
e.ReturnValue as DataSet;
            if 
(underlyingDataSet!=null)
            {
                
// use the underlyDataSet...
            
}
        }

The key to getting access to the underlying object is calling the ReturnValue off of the ObjectDataSourceStatusEventArgs object. ReturnValue is typed as Object, so it is necessary to cast to what the underlying data-type is. In the above example, the underlying data-type is a DataSet.

Published Thursday, August 02, 2007 10:34 AM by Palermo4
Filed under: , , , ,

Comments

# University Update-C#-How To: Access Underlying Data of the ObjectDataSource

Pingback from  University Update-C#-How To: Access Underlying Data of the ObjectDataSource

# re: How To: Access Underlying Data of the ObjectDataSource

Friday, October 05, 2007 10:58 AM by Mihai

Thanks very much for this!

# re: How To: Access Underlying Data of the ObjectDataSource

Wednesday, February 06, 2008 5:44 PM by Dan

Thanks for this!  I spent so much time trying to figure out something so simple as getting a row count.

So now it's easy as:

protected void ObjectDataSource1_Selected

   (object sender, ObjectDataSourceStatusEventArgs e)

       {

         DataSet underlyingDataSet = e.ReturnValue as DataSet;

           if (underlyingDataSet!=null)

           {

               // use the underlyDataSet...

               if (underlyingDataSet.Tables[0].Rows.Count ==0)

               // do something

           }

       }

# re: How To: Access Underlying Data of the ObjectDataSource

Wednesday, January 21, 2009 3:31 PM by Lorenzo

Thank You for your How to... very helpful!

Leave a Comment

(required) 
(required) 
(optional)
(required)