I've automatically populated a DataGrid from a DataTable from a SQL server. I want the user to be able to add or remove which columns are visible. I originally tried this:
public void populateTaskTable(DataTable dt)
{
//add the whole datatable to the datagrid
dg.DataContext = dt.DefaultView;
dg.Columns[0].Visibility = Visibility.Collapsed;
}
For a corresponding xaml (I've tried both with and without the AutoGenerateColumns="True"
<DataGrid Name="dg" ItemsSource="{Binding}" AutoGenerateColumns="True"
<!-- <DataGrid.Columns></DataGrid.Columns> -->
</DataGrid>
Which resulted in a memory violation break. So then I did
MessageBox.Show(dg.Columns.Count());
to see if Columns was being populated, which it wasn't, it output a 0
even though I could see the columns in the program.
I found out from this previous stackoverflow question that "automatically generated columns are not added to the Columns index".
Then from this question I tried updating the DataGrid to get Columns populated like so
taskTable.UpdateLayout();
and
taskTable.Items.Refresh();
Which didn't do anything.
Is there a way to access the properties of an automatically generated DataGrid, or a way to add all of the columns of the DataGrid to the Columns
component?
Thanks in advance.