Reputation: 4951
I'm using C# and WebForms and running into an issue. I have a class like this:
public class Foo
{
public int _touchID;
public string _touchName;
}
Then I have a Dao object that returns a List
of Foo
and I want to bind that list to a DataGrid
.
public List<Foo> getFooList()
{ //get my list and whatnot}
I bind it to my asp:DataGrid
like this:
TouchGrid.DataSource = dao.getFooList();
TouchGrid.DataBind();
The aspx page is like this:
<asp:DataGrid ID="TouchGrid" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundColumn HeaderText="ID" DataField="_touchID"></asp:BoundColumn>
<asp:TemplateColumn HeaderText="Touch">
<ItemTemplate>
<asp:Label ID="touchName" text='<%#DataBinder.Eval(Container.DataItem, "_touchname") %>' runat="server"/>
<%--<div class="touchDescriptionHidden"><%#DataBinder.Eval(Container.DataItem, "_description")%></div>--%>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
When I run the code, I get a runtime exception because
A field or property with the name '_touchID' was not found on the selected data source.
I've tried using DataItem._touchID
but I got the same error using that. I also tried to autogenerate the columns to see if I could get some hint as to why this is failing but I get a message saying
Unable to autogenerate columns for selected datasource
I know I'm missing something but I'm not sure exactly what. If I debug on the DataBind
line and look at the DataSource
, I can see my objects just fine:
TouchGrid.DataSource
[0] - _touchID=1 | _name="stuff" [1] - _touchID=2 | _name="otherStuff"
What is the problem here?
Upvotes: 0
Views: 1154
Reputation: 33809
public class Foo
{
public int TouchID {get; set;}
public string TouchName {get; set;}
}
Also change data binding as follows
<asp:Label ID="touchName"
text='<%# DataBinder.Eval(Container, "DataItem.TouchName") %>' runat="server"/>
Should work..
Upvotes: 1
Reputation: 15663
DataBinding mechanism does not work with class fields, but with class properties.
So you need to convert the fields to properties (also this a requested OOP principle).
public class Foo
{
public int _touchID;
public string _touchName;
}
becomes
public class Foo
{
public int TouchID {get; set;}
public string TouchName {get; set;}
}
Upvotes: 2