Reputation: 17946
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.
Upvotes: 5
Views: 3780
Reputation: 17699
My solution is to use a static method where you pass in the grid and list of column names like this:
public static void CollapseGridColumns(DataGrid grid, List<string> columnNames) { foreach (var column in grid.Columns) { foreach(string columnName in columnNames) { if (column.Header.ToString().ToLower() == columnName.ToLower()) { column.Visibility = Visibility.Collapsed; break; } } } }
Upvotes: 0
Reputation: 73442
Hook up the AutoGeneratingColumn event and hide the column over there.
dataGrid.AutoGeneratingColumn += dataGrid_AutoGeneratingColumn;
void dataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
e.Column.Visibility = Visibility.Collapsed;
}
You may need to conditionally hide the columns, you can use
private void DataGrid_OnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
if (e.PropertyName == "YourProperty")
{
e.Column.Visibility = Visibility.Collapsed;
}
}
Or you can use AutoGeneratedColumns event. It will be fired when all the columns has been generated.
dataGrid.AutoGeneratedColumns += DataGrid1_AutoGeneratedColumns;
void DataGrid1_AutoGeneratedColumns(object sender, EventArgs e)
{
int columnsCount = DataGrid1.Columns.Count;
//You can access the columns here.
}
The link you referred says that Automatically generated columns are not added to the Columns collection. I just noticed that Auto generated columns are indeed added to the collection. It is poor answer that links to the documentation of System.Web.UI.WebControls.DataGrid
which is very wrong.
Upvotes: 6