tags:

views:

28

answers:

2

I have a WPF 4.0 DataGrid that is bound to a DataTable using AutoGenerateColumns=True. The columns are dynamic, however I know there is always going to be a column named ID and I would like to hide this column. Is there a way I can do this?

A: 

I can't speak for 4, however it was not possible in 3.5 SP1, at least without registering for an event which I wanted to avoid at all costs.

What you could do instead is change your generation code to AutoGenerateColumns=False then just place the columns you care about within the XAML as the underlying data will all still be placed within the columns appropriately

            <dg:DataGridTextColumn Header="Display" Binding="{Binding DisplayName}"/>
            <dg:DataGridTextColumn Header="Host" Binding="{Binding HostName}"/>
            <dg:DataGridTextColumn Header="Database" Binding="{Binding Database}"/>
            <dg:DataGridTextColumn Header="Username" Binding="{Binding Username}"/>
            <dg:DataGridTextColumn Header="Password" Binding="{Binding Password}"/>

This will allow you to display the only columns you care about in relation to the underlying model as well as change the Header to display as you see fit, so you are not tied to the Property name on the model.

Aaron
That is not an option for me since I do not know the column names beforehand
Rachel
This is not being generated from a model? What does the data look like...?
Aaron
The model just contains a DataTable property which contains the data to display in the DataGrid.
Rachel
+1  A: 

in your datagrid, subscribe for the AutoGeneratingColumn event, the event args (DataGridAutoGeneratingColumnEventArgs) has the column name and a "Cancel", if the column name is ID then set Cancel = true. should do the trick.

Alex Lo
That'd work...although it immediately goes against the MVVM pattern...but will no doubt work.
Aaron
Thank you, that will work nicely. I'm not too concerned with MVVM in this case since the DataGrid is part of a custom UserControl and I have no problems using code-behind if it is something that only affects the View.
Rachel
@Aaron, if you're relying on the View to generate the MV, then i think you're going to find it's not adherent to MVVM :)
Alex Lo
@Alex MV = VM???
Aaron
@Aaron, yes that's right
Alex Lo
You can build a view model that exposes both a `DataTable` and a list of columns that auto-generation should skip, have the `AutoGeneratingColumn` event use that list, and tuck yourself into bed at night secure in the knowledge that you've still separated the view from the view model.
Robert Rossney