How to hide a DataGrid column in WPF using C#

In a situation where I have a DataGrid which is being bound to a List of a specific class and the DataGrid has AutoGenerateColumns set to true, I found myself needing a way to hide some of the columns which I did not want to present to a user. Below is an example of binding a class to a DataGrid in WPF with C#.

IList<Parent> resultSet = BaseClase.ExecuteQuery<Parent>(query);
dataGrid1.ItemsSource = resultSet; 

The parent class had some ID’s, timestamps and flags which I did not want to be shown to the user in the DataGrid. Setting the DataGrid column visibility to hidden is all that is required.

dataGrid1.Columns[0].Visibility = System.Windows.Visibility.Hidden;

Note that the properties in your class are added to the DataGrid in the order in which they are ordered in your class, the first one starting with 0. Simply reference the index of the column you want to hide and it will not show in the DataGrid.

However, when you need to capture the data from the DataGrid, it is available to you.

Parent pnt = (Parent)dataGrid1.SelectedItem;

Then simply use pnt to access any of the properties within the class.