Sync column names of DataGrid and DataTable in WPF

983 Views Asked by At

I have a DataGrid. When I change one of the DataGrid's column names, I want an event to arise so that the column name of the DataTable (the ItemSource of DataGrid) changes as well.

How can I sync the column names of the DataGrid and DataTable?

EDIT

I have datagrid like this with 6 column:

<wpfc4:RGrid x:Name="dgrid" Grid.Row="2" ItemsSource="{Binding Model.CurrentDataTable}" Style="{DynamicResource DataGridRStyle}" AutoGenerateColumns="True"></wpfc4:RGrid>

This RemoveSelectedColumn function :

 private void RemoveSelectedColumn()
    {
        DataGridColumn toRemove = this.Columns[_selectedColumnIndex];
        DataView view = this.ItemsSource as DataView;

        view.Table.Columns.Remove(toRemove.Header.ToString());  
        // deleting column from datatable.

        this.UpdateLayout();
        this.Items.Refresh();
    }

It's deleting from datatable but datagrid still has 6 column but deleted column has blank value. How I cna update datagrid so it shows only 4 column when i deleted 2 columns from datatable.

2

There are 2 best solutions below

1
On

If possible, I would try to reverse this so that any time you change the name of one of the columns in the DataTable, the DataGrid gets updated.

If you have AutoGenerateColumns set to true on your DataGrid, this should be quite straightforward:

  1. Bind your DataGrid to your DataTable (using the ItemsSource property of the DataGrid).
  2. Make sure the class that contains your DataGrid property implements INotifyPropertyChanged, then raise the PropertyChanged event any time a column name on your DataTable changes.
0
On

I also have the same problem what I did itemsource table first take in the temp variable and make itemsource table object null , then remove the column and reassign the value to the itemsource table object...this works for me..

DataTable tempTable = ItemsourceDataTable;
ItemsourceDataTable= null;
tempTable.Columns.Remove("ColumnHeaderName");
ItemsourceDataTable= tempTable ;