How to insert into ObjectDataSource a list of items from code behind , and NOT from the aspx?

2k Views Asked by At

I have the following declaration in my .ASPX :

<asp:ObjectDataSource ID="ODS" runat="server" 
    SelectMethod="GetPlayersData" DataObjectTypeName="DAL.MyObject">
</asp:ObjectDataSource>

How can I place the data in the ObjectDataSource from the code behind ?

This :

var items = MyFunctions.GetPlayersData().ToList<object>();
ODS.SelectParameters = (ParameterCollection)items;

Doesn't work.

1

There are 1 best solutions below

0
On

If I understand that you want to call DAL.MyObject.GetPlayersData() and get that data to a data bound control, you don't necessarily need an ObjectDataSource. You can simply wire the data into the DataSource property and then call the DataBind method:

 GridView myGridView;
 //Set Data Source
 myGridView.DataSource = DAL.MyObject.GetPlayersData();
 //Have GridView pull in the data.
 myGridView.DataBind();

Alternatively, if you still want to use some of the features of ObjectDataSource to make two way data binding nicer, you can build up a ObjectDataSource programatically in your code behind. The process is very similiar to the declarative syntax:

  ODS.SelectMethod = "GetPlayersData",
  ODS.DataObjectTypeName = "DAL.MyObject",
  ODS.TypeName = "MyFunctions"

The ObjectDataSource will call GetPlayersData() itself, so you don't need to call it yourself.

But if for some odd reason you need to, you can override the ReturnValue in the Selected event:

 ods.Selected += (sender, args) =>
 {
   //This will cause GetPlayersData() to be called twice
   args.ReturnValue = MyFunctions.GetPlayersData();
 }