I have a GridView bound to an ICollection<UserAnswer> that needs to show two columns:
<asp:GridView ID='UserAnswersGridView' runat='server'> <Columns> <asp:BoundField DataField='Question.Name' HeaderText='Question Name' SortExpression='QuestionID' /> <asp:BoundField DataField='Score' HeaderText='Score' SortExpression='Score' /> </Columns> </asp:GridView>
But I get the error:
A field or property with the name ‘Question.Name’ was not found on the selected data source.
Each UserAnswer has a QuestionId value which is what I would use to query the question name. In code, I would just call userAssessment.Question.Name, but how would I do this with a bound column in a GridView without creating a new type?
For reference this is the method that returns the data:
public static ICollection<UserAnswer> GetUserAnswers(Int32 userAssessmentId) { DataContext database = new DataContext(GetConnectionString()); return database.UserAnswers.Where(u => u.UserAssessmentId == userAssessmentId).ToList(); }
Sorry if this explanation isn’t very clear!
I believe that
GridViewonly supports properties of the immediate type. Is repeater or anything similar an option? That gives you more flexibility.Alternatively, you can add shim properties to the type via a partial class:
You can’t use this in filters (
Whereetc), but you should be able to use it on returned objects without issue. Note that you might want to useLoadWithto save the round-trips: