Interesting bit of information here regarding the
ObjectDataSource control in ASP.NET 2.0. Let’s say I have an class that I
want to set as the data source and the class contains a method that returns a
collection. For example, a Person class that has a method named GetPeople as
follows:
public
List<Person>
GetPeople() {
List<Person>
list = new List<Person>();
list.Add(new
Person("Sean",
32));
list.Add(new
Person("Brittany",
2));
return list;
}
Behind the scenes, the ObjectDataSource control uses
reflection to invoke the method GetPeople() behind the scenes based on the
server side tags as follows:
<asp:ObjectDataSource
ID="ObjectDataSource1"
runat="server"
TypeName="Person"
SelectMethod="GetPeople"></asp:ObjectDataSource>
On the same page, I have grid view that is bound to the
ObjectDataSource control as follows.
<asp:GridView
ID="GridView1"
runat="server"
DataSourceID="ObjectDataSource1"
ForeColor="#333333"
GridLines="None"
CellPadding="4">
<FooterStyle
ForeColor="White"
Font-Bold="True"
BackColor="#5D7B9D"
/>
<RowStyle
ForeColor="#333333"
BackColor="#F7F6F3"
/>
<PagerStyle
ForeColor="White"
HorizontalAlign="Center"
BackColor="#284775"
/>
<SelectedRowStyle
ForeColor="#333333"
Font-Bold="True"
BackColor="#E2DED6"
/>
<HeaderStyle
ForeColor="White"
Font-Bold="True"
BackColor="#5D7B9D"
/>
<EditRowStyle
Font-Italic="False"
Font-Bold="False"
BackColor="#999999"
/>
<AlternatingRowStyle
ForeColor="#284775"
BackColor="White"
/>
</asp:GridView>
The first time I tried running my little test app, I kept
getting a run-time exception that said, “The data source for GridView with id
'GridView1' did not have any properties or attributes from which to generate
columns. Ensure that your data source has content.” Yuck!
It turns out that the reflection happening behind the
scenes does not work with fields.
public
class Person
{
...
//Uh oh! Won't work!!!!!!!
public
string Name;
public
int Age;
...
Well, it's not that I buy into
what JayBaz says about properties. I was just hastily writing some test code
without any regard to my flippancy. As soon as a changed the public fields to
properties, TADA!
public
class Person
{
private string
_name;
private int
_age;
public Person() { }
public Person(string
name, int age) {
this._name = name;
this._age = age;
}
public string
Name {
get { return
_name; }
set { _name = value;
}
}
public int
Age {
get { return
_age; }
set { _age = value;
}
}
public List<Person>
GetPeople() {
List<Person>
list = new List<Person>();
list.Add(new
Person("Sean",
32));
list.Add(new
Person("Brittany",
2));
return list;
}
}
Ever hear the phrase “read the f---ing manual?” Well, it
does turn out that
the docs tell you this if you dig in far enough. Since ASP.NET 2.0 is still in BETA, I figured I’d share this in case anyone else runs
into the same issue. J