I recently ran into a situation where I needed an ObjectDataSource in order to use the sort and filter capabilities of the SharePoint SPGridView control, however, my data was already in a DataTable.
I found out that I could use the ObjectCreating event of the ObjectDataSource in order to set the control to an existing data object, such as a DataTable. I was pretty excited to see that I would be able to take the existing DataTable and expose it as an ObjectDataSource. That excitement was short lived as I continued to have problems getting it to work with the SPDataView control. ?
The issue is that the ObjectDataSource was configured to call the Select method of the DataTable whenever the SPGridView control requested data. This caused the ObjectDataSource to return a DataRow array which the SPGridView did not understand. I needed the ObjectDataSource to return the data as a complete DataTable and not DataRow array.
The solution that I arrived at is to create a very simple wrapper class around my DataTable object that returned the original DataTable when a method is called on the wrapper class. Once implemented I had a perfect rendering SPGridView with both filtering and sorting enabled. ?
Below is an example of the wrapper class:
public class DataTableWrapper
private DataTable _dt = new DataTable();
public DataTableWrapper(DataTable dt)
_dt = dt;
public DataTable GetTable()
Here is an example of connecting this up to the ObjectDataSource:
ObjectDataSource ds = new ObjectDataSource();
ds.ID = “myDataSource”;
ds.TypeName=”[…strong name of your DataTableWrapper class here]”;
ds.ObjectCreating += new ObjectDataSourceObjectEventHandler(ds_ObjectCreating);
And here is the ObjectDataSource ObjectCreating event handler:
void ds_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
myDataTable = new DataTableWrapper(sourceDataTable);
e.ObjectInstance = myDataTable;
Things to note about the above samples:
- The original data source sourceDataTable was defined with class scope. This allows the ds_ObjectCreating method to access it.
- myDataTable was defined with class scope.
- The TypeName of the ObjectDataSource must be the full strong type name for the DataTableWrapper object.
Maybe there is a simpler way of doing this. I would love feedback if you have any suggestions.