Databinding Class Data
ASP.NET, OO By Dave Ward. Updated April 18, 2007It 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?
I appreciate all of your comments, but please try to stay on topic. If you have a question unrelated to this post, I recommend posting on the ASP.NET forums or Stack Overflow instead.
If you're replying to another comment, use the threading feature by clicking "Reply to this comment" before submitting your own.



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.
Great post, thanks for the info. Your site is a valuable resource for new ASP.NET AJAX programmers like myself! Keep up the good work!