Databinding Class Data
ASP.NET, OO By Dave Ward on December 21st, 2006It took me a few minutes to figure this out and Google was surprisingly unhelpful so hopefully this will be useful to others.
When databinding objects, only properties are available. To my dismay, simply making class fields public isn’t enough. Even though the field is right there, publicly accessible, the databinder acts as if it’s not.
Consider a class, Payment:
public class Payment { public decimal Amount; Payment() { } }
We might use this like so:
<asp:gridview runat="server" id="dgPayments"> <Columns> <asp:TemplateColumn HeaderText="Amount"> <ItemTemplate> <%# DataBinder.Eval(Container.DataItem, "Amount") %> </ItemTemplate> </asp:TemplateColumn> </Columns> </asp:gridview>
protected void Page_Load(object sender, System.EventArgs e) { List<Payment> Payments = new List<Payment>(); // Code here to fill Payments with your collection of Payment objects. dgPayments.DataSource = Payments; dgPayments.DataBind(); }
On databinding, this throws an error claiming that there’s no Amount available to bind.
Modify the class to encapsulate the field as a property like so:
public class Payment { private decimal _amount; public decimal Amount { get { return _amount; } set { _amount = value; } } Payment() { } }
Now, it works.
Similar posts
What do you think? Your comments are welcomed.
I appreciate all of your comments, questions, and other feedback, but please try to stay on topic. If you have a question unrelated to this post, I recommend posting on the ASP.NET forums. If you post there and then contact me with a link to the post, I'll try to take a look at it for you.
If you're replying to an existing comment, please use the threading feature. To do this, click the "Reply to this comment" link underneath the comment you're replying to.

Comments
Thanks for the example. I am trying to use this pattern. Can you show an example of the data binding?
This bit me in the ass a couple times. It makes sense, but it’s not obvious and can be a head-scratcher, particularly if you only directly references fields one or two places in the mix.
Sergi, I’ve updated the example to have some of the code needed to create a generic collection of Payment objects and databind them to a GridView. Hope that helps.