NomenNescio
NomenNescio

Reputation: 3030

Populate a Datagrid with a Linq query

I have the following datagrid in a wpf form:

<DataGrid Name="DataGrid" AutoGenerateColumns="False" VerticalScrollBarVisibility="Auto">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Name" Width="200"></DataGridTextColumn>
        <DataGridTextColumn Header="Text" Width="200"></DataGridTextColumn>
        <DataGridTemplateColumn Header="Edit" Width="50">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Button>View Details</Button>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

And I'd like to populate it from my code. I use a linq statement to get the values I'd like to put in the datagrid

var query =
    (
        from modules ...
        join ...
        join ...
        where ...
        select new { ID = modules.ID, Name = strings.Name, Text = stringTexts.Text }
    );

I'd like to populate the columns 'Name' and 'Text' with Name and Text from the query, but I also want there to be a button in each row, and when that button is pressed, I have to know the ID of the row that was pressed, but the ID does not have to show up on the grid.

How do I populate the grid with these values?

Upvotes: 0

Views: 6016

Answers (2)

SarahK
SarahK

Reputation: 624

This should work for you:

Grid.DataSource = from x in modules
                  select new
                  {
                      x.Name,
                      x.Text
                  };
Grid.DataBind();

Best of luck!

Upvotes: 0

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48600

Tell columns to bind to a property using

<DataGridTextColumn Header="Name" Width="200" Binding="{Binding Name}" />

and so on for other columns.

Then in code behind

DataGrid.ItemsSource = query;

Upvotes: 2

Related Questions