In WPF, how can I bind a datagrid column to a specific column of a datatable?

半城伤御伤魂 提交于 2019-12-03 00:21:34

Bind your DataTable to the DataGrid, set the AutoGenerateColumns to False, and then add whatever columns you want to DataGrid.Columns. Here's an example using a DataTable called Collection, with two columns: ID and Value.

<DataGrid
    ItemsSource="{Binding Path=Collection}"
    AutoGenerateColumns=False
    >

    <DataGrid.Columns>
        <DataGridTextColumn Header="Id" Binding="{Binding Path=Id}" />
        <DataGridTextColumn Header="Value" Binding="{Binding Path=Value}" />
    </DataGrid.Columns>
</DataGrid>
Andrey

XAML binding would not work for me because my DataTable is generated at runtime so there is nothing to bind to at design time. Anyway, I stumbled on how to do what I wanted here.

My problems were because for some reason there was no error thrown when I would set ItemSource to the table itself, instead of the table's DefaultView, even though, as I later read, the table does not implement the required interface. But without any errors to tell me difference I had nothing to go on to find why my grid would display as empty.

DataGridName.DataContext = DataSetName.DataTableName;
DataGridName.ItemsSource = DataSetName.DataTableName.DefaultView;

((DataGridTextColumn)DataGridName.Columns[1]).Binding = new Binding("DataTableColumnName1");
((DataGridTextColumn)DataGridName.Columns[0]).Binding = new Binding("DataTableColumnName2");
((DataGridTextColumn)DataGridName.Columns[2]).Binding = new Binding("DataTableColumnName3");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!