How to change the SelectMethod of ObjectDataSource programatically?
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="hiddenUser开发者_运维技巧name" 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 , DepartmentCodeI 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
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
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.objectdatasource.selecting%28v=vs.90%29.aspx
http://www.asp.net/data-access/tutorials/programmatically-setting-the-objectdatasource-s-parameter-values-vb
Hope this will help..
Happy Programming!
Try this
GetProjectsDataSource.SelectMethod = "GetProjectByUsernameDeptCd";
Parameter p1 = new Parameter("parameter1 ",TypeCode.String);
Parameter p2 = new Parameter("parameter2 ",TypeCode.String);
GetProjectsDataSource.SelectParameters.Add(p1);
GetProjectsDataSource.SelectParameters.Add(p2);
Have you tried the C# codebehind? Instead of defining it in the aspx markup, go to the codebehind file, and do it there.
精彩评论