Can you databind an asp.net gridview to a field in a base class?
I have the following classes (pseudocode):
- Item ( int Field1 )
- ItemDetail : Item (int Field2, string field3)
If I set ItemDetail as the datasource for an asp.net gridview:
grid.DataSource = new List<ItemDetail>();
grid.DataBind();
Can I use Field1 in the GridView? If so, what is the correct DataBinder syntax? The following code blows up trying to cast to an Item:
<%# DataBinder.Eval(Container.DataItem, "Field1") %>
Thanks in开发者_如何学C advance for any help.
EDIT: And I'm a moron. I had copied the gridview and was calling a RowDataBound event handler for a different grid... Sorry to have wasted everyones time, but there is some good info here regardless if anyone has the same question. In the end, the public properties of the base class are binding correctly. Thanks!
If your base class property is public, you shouldn't have an issue as long as you're also initializing it in your child constructors.
Also, I'm not sure if your example binding is pseudocode or not, but you have to bind a grid to an IListSource, IEnumerable, or IDataSource, so you need a Collection, List, IQueryable, etc. of ItemDetails.
That would require your ItemDetail class to have a property called Field1. The rest of the syntax is good though.
<%# DataBinder.Eval(Container.DataItem, "Field1") %>
ItemDetal itemDetail = new ItemDetail();
itemDetail.Field1 = 100;
- where Field1 is an accessable property, and not just a private field in your class. This should write out 100 in your grid.
精彩评论