Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only display certain columns in DataGrid from an Entity Object

Tags:

c#

sql

wpf

xaml

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!!!!

like image 595
Josh Avatar asked Feb 23 '12 18:02

Josh


People also ask

How do I get specific columns in Entity Framework?

In Entity Framework Core we can select specific columns by using either anonymous types or DTOs.

How do I add a DataGrid toolbox?

Windows Forms DataGrid (SfDataGrid) control can be added to the application by dragging it from Toolbox and dropping it in Designer. The required assembly references will be added automatically.


1 Answers

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.

like image 156
Phil Avatar answered Nov 03 '22 08:11

Phil