How can I Bind a List of custom class objects to a Gridview's Datasource (getting "A field or property ... not found on the ... data source")?


To avoid querying the Database on the first loading of the page, I want to populate a List of a custom class to the GridView.

I'm trying to do it this way:

protected void Page_Load(object sender, EventArgs e)
    List<MoviesGridDisplayColumns> listStartupData = new List<MoviesGridDisplayColumns>();
    MoviesGridDisplayColumns mgdc;

    mgdc = new MoviesGridDisplayColumns();
    mgdc.MovieTitle = "War of the Buttons";
    mgdc.MPAARating = "PG";
    mgdc.IMDBRating = 7.5;
    mgdc.Minutes = 94;
    mgdc.YearReleased = "1994";

    mgdc = new MoviesGridDisplayColumns();
    mgdc.MovieTitle = "The Trip to Bountiful";
    mgdc.MPAARating = "PG";
    mgdc.IMDBRating = 7.5;
    mgdc.Minutes = 108;
    mgdc.YearReleased = "1985";

    . . .

    GridView1.DataSource = listStartupData;

...but on the penultimate line above I get:

"System.Web.HttpException HResult=0x80004005 Message=A field or property with the name 'MovieTitle' was not found on the selected data source."

The selected data source is the List of MoviesGridDisplayColumns objects, which does indeed have a MovieTitle member. So what gives?

The custom class is:

public class MoviesGridDisplayColumns
    public string MovieTitle = string.Empty;
    public double IMDBRating = 0.0;
    public string MPAARating = string.Empty;
    public string YearReleased = string.Empty;
    public int Minutes;

...and the GridView appears in the .aspx file thus:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnDataBound="GridView1_DataBound" OnPreRender="GridView1_PreRender">
        <asp:BoundField DataField="MovieTitle" HeaderText="MovieTitle" SortExpression="MovieTitle" />
        <asp:BoundField DataField="IMDBRating" HeaderText="IMDBRating" SortExpression="IMDBRating" />
        <asp:BoundField DataField="MPAARating" HeaderText="MPAARating" SortExpression="MPAARating" />
        <asp:BoundField DataField="YearReleased" HeaderText="YearReleased" SortExpression="YearReleased" />
        <asp:BoundField DataField="Minutes" HeaderText="Minutes" SortExpression="Minutes" />

1 Answer


The fields in your class are missing the getter methods. You can change the MoviesGridDisplayColumns to the following.

public class MoviesGridDisplayColumns
        public string MovieTitle { get; set; } = string.Empty;
        public double IMDBRating { get; set; } = 0.0;
        public string MPAARating { get; set; } = string.Empty;
        public string YearReleased { get; set; } = string.Empty;
        public int Minutes { get; set; }
answered on Stack Overflow Oct 5, 2020 by Ali Ihsan

User contributions licensed under CC BY-SA 3.0