DataGrid Ad Hoc columns

Feb 10, 2009 at 5:10 AM
Hi all, I have a DataGrid that I use to display object data with.  Everything seems to be working fine, however the application sometimes does not need to display the full objects data just a few of the fields instead of all of them.  The problem is that I have no way of knowing ahead of time which fields until the user selects them.  Is there any way to either hide columns or create an ad-hoc object at runtime?

Thank you,
Feb 10, 2009 at 6:06 AM

Try setting Visibility="Hidden" on the columns you wish to hide.

Colin E.
-- - my WPF blog - WPF DataGrid Practical Examples
Feb 10, 2009 at 7:11 AM
Thanks Colin, heres the wiered thing though.  After I set the ItemsSource property of the DataGrid I see no columns when I step through the debugger.  In fact I put in a foreach loop to iterate through the column collection and it skips right over it.  Here's a snippet.


// get a DataGrid control and populate with data



DataGrid dataGrid = new DataGrid();


dataGrid.ItemsSource = selectedFile.CreateRunInstances();



// add the DataGrid to the TabItem


dataTab.Content = dataGrid;


foreach (DataGridColumn col in dataGrid.Columns)



col.Visibility =





// add the TabItem to the TabControl



Feb 10, 2009 at 8:29 AM

How about handling the Loaded event of the DataGrid, the iterating over the columns collection? The visual components of a control are not fully constructed when you first create an instance of a control. From MSDN, the Loaded event "Occurs when the element is laid out, rendered, and ready for interaction."

This might help.

Colin E.
-- - my WPF blog - WPF DataGrid Practical Examples