Passing an object to ObjectDataSource

Wednesday, May 10th, 2006 | .NET

I like the ObjectDataSources in some occasions, even if liked the .NET 1.1 way of working with data better. I have played around with ObejctdataSources for a while, and it hit me that it's not intuitive to pass an object as the parameter.  The Visual Studio designer has functionality for passing parameters to the business objects, but only as strings. This is actually a limitation to the Parameter class as the DefaultValue is of type string.

Coding standards suggest that a method should have 7 parameters or less (some say even 5), and databinding methods can have a lot of parameters based on what data to fetch. A good way is to pass a struct or object instead of several parameters.

So it's not possible to initially pass an object as a parameter. You have to do it in an event instead. The following solution illustrates how it could be done:

  • Select the ObjectDataSource in the designer and select the Events for the ObjectdataSource.
  • Double click the Selecting event. This generates a callback method for the event in your code behind file.
  • The method should look something like this:

protected void ObjectDataSourceNewsList_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
{
NewsArchive newsArchive = new NewsArchive();
newsArchive.Language = "no";
newsArchive.Country = "NO";
e.InputParameters["newsArchive"] = newsArchive;
}

The newsArchive parameter is defined in the ObjectDataSource as of type Object. This works fine, but it's rather strange that you have to define the parameter in an event and not by the parameters in the ObjectDataSource.

Tags:

2 Comments to Passing an object to ObjectDataSource

Justas Birgiolas
November 25, 2008

Def agree with you on the DefaultValue being of type string limitation.

Thanks for the sample.

Tim
November 5, 2009

Awesome tip. I have been looking for a way to do this for a while.

Leave a comment

Search

Knut Hamang

This is the official site for Knut Hamang. I am a professional technical consultant specialized in Microsoft and .NET technologies and platforms. I work as an independent consultant in Norway and have more than 10 years of professional experience. To get in contact with me, please send me an email or check my public profile on View Knut Hamang's profile on LinkedIn