How to change the SelectMethod of ObjectDataSource programatically?

Sherwin picture Sherwin · Apr 25, 2011 · Viewed 14.9k times · Source

Suppose I have a given ObjectDataSource, this objectdatasource "SelectMethod" property is set to "GetProjectsByUsername" of a class Project and accepting one parameter.

 <asp:ObjectDataSource ID="GetProjectsDataSource" runat="server" SelectMethod="GetProjectsByUsername"
    TypeName="BusinessLayer.Project">
    <SelectParameters>
        <asp:ControlParameter ControlID="hiddenUsername" Name="username" PropertyName="Value"
            Type="String" />
    </SelectParameters>
</asp:ObjectDataSource>

Now, Is it possible to change the SelectMethod property of this ObjectDataSource to a method that accepts two parameters during OnInit method? for example

MethodName : GetProjectByUsernameDeptCd()
Parameters : Username , DepartmentCode

I would like to change the select method by User Roles. I've tried to search SO and Internet but it seems that I have no luck on it. Anyway I wanted to do like:

if ( Role is Admin )
Use the default SelectMethod and Parameters that is declared in ASPX
else
Change the SelectMethod to "GetProjectByUsernameDeptCd"
Set parameter1 = value1
Set parameter2 = value2

Or I was thinking if there are other better ways to do this.

Thank You and Best Regards, Sherwin

Answer

Saurabh picture Saurabh · Apr 25, 2011

Yes, you can do this in the OnSelecting event of the ObjectDataSource in a code-behind file.

Ex.

protected void ObjectDataSource1_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
    {
        ObjectDataSource1.SelectMethod = "<YourSelectMethod>";
        e.InputParameters.Clear(); // this is a different method with new parameters.
        e.InputParameters.Add("Param1", "Value1");
        e.InputParameters.Add("Param2", "Value2");
        e.InputParameters.Add("Param3", "Value3");
    }

For more details please read below articles : 1. http://weblogs.asp.net/rajbk/pages/426642.aspx

  1. http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.objectdatasource.selecting%28v=vs.90%29.aspx

  2. http://www.asp.net/data-access/tutorials/programmatically-setting-the-objectdatasource-s-parameter-values-vb

Hope this will help..

Happy Programming!