Josh
Josh

Reputation: 657

Only display certain columns in DataGrid from an Entity Object

I am trying to populate a DataGrid with a SQL query on an Entity Model created in VS2010.

    public List<MovieTable> LoadMoviesMethod()
    {
        ObjectQuery<MovieTable> _movies = dataEntities.MovieTables;

        var query =
            from MovieTable in _movies
            //where MovieTable.Rating == "R"
            //orderby MovieTable.id
            select MovieTable;

       return query.ToList();
    }

The object MovieTable is automatically generated when I import my database, but when it displays on the grid it shows the more information than I would like (id, EntityKey and EntityState). Trying to select certain properties in the object I get strings back and the return statement complains. Is there a way to select certain members of the MovieTable for display on the datagrid? Maybe specify the columns I would like to display? Seems simple enough, but I guess I'm not good enough to figure it out!!!!

Upvotes: 10

Views: 12877

Answers (1)

Phil
Phil

Reputation: 42991

You need to specify AutoGenerateColumns="False" and then specify the columns you require explicitly. Something like

    <DataGrid ItemsSource="{Binding Items}" AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Id" Binding="{Binding Id}"/>
            <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
            ... etc

There are a few different column types - text, combo-box, check-box, hyperlink, template...

This blog post may be useful.

Upvotes: 29

Related Questions