WPF DataGrid - DataSet - dynamical Binding?

May 10, 2010 at 7:01 PM

Hello together,

I want to bind a WPF Datagrid dynamically to a DataSet Table. I get different results (different Columnheader Names) from database requests and I want to show all these results in the same Datagrid.

Unless the Columnheader of the DataSet Table doesn't vary, its no problem. For instance if the Name of the first Columnheader is "Name" I can use the following code:

<my:DataGrid AutoGenerateColumns="False" Name="Datagrid">
        <my:DataGridTextColumn Header="Name" Binding="{Binding Name}" />

and in the code behind:

Datagrid.ItemsSource = Dataset.Tables["Data"].DefaultView;
But how can I bind the Column to the Datagrid if the Columnheader varies? Is there a way of dynamically binding?

Thanks in advance

Jun 2, 2010 at 12:29 PM


You could add the columns and their bindings in code:

foreach (String propertyName in listOfPropertyNames)

   DataGridTextColumn textColumn = new DataGridTextColumn()
      Header = propertyName,
      Binding = new Binding()
         Path = new PropertyPath(propertyName)



However, I have a similar problem, as I haven't figured out how to do the same thing with DataGridTemplateColumns
that are using DataTemplateSelectors, as there doesn't exist Binding that I could somehow use for the properties.

I have PropertyNames in a list that match some properties of CustomTypeDescriptor (within a collection), and I need
to create templatecolumns for each property. Can anyone help me with this?

Thank you in advance.

Jun 2, 2010 at 1:37 PM

To be more precise:

I have object that has properties 'a' 'b' 'c' 'd' and so on (and the names are dynamic and also the types can change).

I have templates for different types. And if I have to list the properties of a single element I can just bind to the value in xaml and use datatemplateselector (in datagridtemplatecolumn) which will pick the correct template.

However, when I'm listing several of the elements, how can I use the selectors and the templates? How do I get the correct property to the template?

I'm stuck at:


foreach (String a in commonPropertyNames)
   DataGridTemplateColumn templColumn = new DataGridTemplateColumn();
   templColumn.IsReadOnly = false;
   templColumn.CellEditingTemplateSelector =multiExpanderDG._dataGrid.FindResource("myDataTemplateEditorSelector") as DataTemplateSelector;
   templColumn.CellTemplateSelector =multiExpanderDG._dataGrid.FindResource("myDataTemplateSelector") as DataTemplateSelector;

 // How do I bind the data to it...?  I can't do it with the binding like in the previous post