Correct use of ObjectDataSource
Hello!
I am creating a User Control that will display data in a GridView control. We are using an n-tier architecture and the data in question is retrieved from our database and returned to us as ReadOnlyCollection. OurNewObject is a class that contains several properties and an empty constructor that takes no parameters — it's in the following namespace: Acme.ObjectModel.
In a custom control, I have the following:
<asp:GridView ID="ourGrid" runat="server" DataSourceID="ourDataSource">
<columns>
<asp:BoundField DataField="Name" HeaderText="Full Name" />
<asp:BoundField DataField="Gender" HeaderText="Gender" />
<asp:BoundField DataField="BirthYear" HeaderText="Year of Birth" />
<asp:BoundField DataField="JoinDate" HeaderText="Date Joined" />
</columns>
</asp:GridView>
<asp:ObjectDataSource ID="ourDataSource" runat="server" SelectMethod="GetTopUsers" TypeName="Acme.Model.OurNewObject">
</asp:ObjectDataSource>
In the user control code, I have the following public method:
public ReadOnlyCollection<OurNewObject> GetTopUsers()
{
return (OurDataProxy.GetJustTheTopUsers());
}
When I put a user control on a web form and run it, I get the following message:
ObjectDataSource 'ourDataSource' could not find non-generic GetTopUsers method that has no parameters.
So my questions are:
- Am I using ObjectDataSource wrong?
- Is there a better way to use ObjectDataSource in this situation?
Thank.
source to share
I believe the two attributes are not the problem.
First your GetTopUsers () method adds this attribute
[System.ComponentModel.DataObjectMethodAttribute
(System.ComponentModel.DataObjectMethodType.Select, true)]
Then in your actual OurNewObject class add this attribute
[System.ComponentModel.DataObject]
source to share
Typically, you will create a separate object that contains your data access methods, instead of placing the methods in your code. A single object can be instance or static, but the object itself must have a parameterless constructor (or no constructor at all).
In addition, the TypeName property on the ObjectDataSource must reference the name of the above single object. Example:
public class SampleDataObject
{
public ICollection<OurNewObject> GetTopUsers()
{
//[...]
}
}
The attributes mentioned above: [System.ComponentModel.DataObject (true)] at the class level and [System.ComponentModel.DataObjectMethod (DataObjectMethodType.Select)] in the getter method is not required, but will help in design-time support by filtering out other types when looking for classes to bind the ObjectDataSource before.
source to share