Using BLL objects with Parameterized Constructors in an ObjectDataSource
If you use BLL objects with ObjectDataSources to populate your GridViews, DropDownLists, etc, the ObjectDataSource tries to instantiate your BLL object using a parameterless constructor. If you don't have a parameterless constructor (I usually don't) available, you'll get and error like:
No parameterless constructor defined for this object.
Description: An un-handled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.MissingMethodException: No parameterless constructor defined for this object.
The way to get around this problem is to handle the ObjectDataSource's "OnObjectCreating" property and instantiate the object with any necessary parameters, and then assign that object to the e.ObjectInstance property. A quick and easy sample is below:
protected void objBLLClass_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
{
BLLClass bClass = new BLLClass(param1, param2);
e.ObjectInstance = bClass;
}
-- If you aren't using ObjectsDataSources yet, I highly recommend it for creating powerful, multi-tiered applications. There is a great intro-level series on 3-Tier Data Access at the ASP.NET main site. Once you understand the .NET 2.0 data model, there are many ways to customize the default objects to create really powerful applications! --