Recently, someone asked on SloDug forum, how can he persuade ObjectDatasource to use custom constructor with some parameters. The answer is: use OnObjectCreating event. Before using this, you must understand how objectdatasource works.
See example below:
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
SelectMethod="MySelectMethod"
TypeName="MyType">
</asp:ObjectDataSource>
TypeName is the name of the class, which contains the method you want to call, whereas SelectMethod (in this case) is the method name, which you will use to perform select operation and return data to the control. The control then perfom binding to the data control. The trick here is in TypeName. Instance of this object is created (default constructor is called) before select method is retrieved and called (logical). Then instance calls the method, specified in SelectMethod property.
OnObjectCreating event is fired by the ObjectDataSource control just before it tries to call your method. So, here can you create you custom constructor and pass any argument you like to perform whatever action you want to do. Then you assign your custom object to the ObjectInstance property of the ObjectDataSourceEventArgs parameter and this instance will be called instead of default constructor.
Code example:
Lets say you have a buisness class, that has two parameters. Something like this:
public class BLL {
public BLL() { ...} //default
public BLL(int maxNumberRecord, string connectionString) ....
public DataTable GetData().... //call some data
}
and objectdatasource defined like this
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
SelectMethod="GetData"
TypeName="BLL">
</asp:ObjectDataSource>
Now you want to set the other constructor with max number record and with connection string to another database (lame example, but you get the point). Just implement OnObjectCreating event and create and instance of desired custom constructor, in our case BLL(int, string).
protected void ObjectDataSource1_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
{
BLL bll = new BLL(10, "connectionString");
e.ObjectInstance = bll;
}
And html has now this structure:
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
SelectMethod="GetData"
TypeName="BLL" OnObjectCreating="ObjectDataSource1_ObjectCreating">
</asp:ObjectDataSource>
Compile, try and let me know, if any errors occured. More on this link.