Programmatically binding a WPF datagrid to a typed dataset datatable

Feb 3, 2009 at 7:58 PM
I have been trying to digest a common methodology that is standard practice for binding a WPF datagrid to an underlying table from a typed dataset in VB.Net. Most examples I have seen are XAML-based, but I would like to be able to define a binding at runtime in VB.Net code so I can use one datagrid to display data from multiple tables on demand.

I managed to piece together a test project that propagated changes made in the datagrid back to the actual database, but the binding I used was static XAML and I can't seem to get the same functionality in straight VB code. Here is part of the code:

 <dg:DataGrid   
            Margin="10,10,15,1" 
            Name="MyDataGrid" 
             AutoGenerateColumns="False">
              <dg:DataGrid.Columns>
                  <dg:DataGridTextColumn 
             Header="PatID"
             Binding="{Binding Path=PatID}">
                </dg:DataGridTextColumn>
                <dg:DataGridTextColumn 
                    Header="Comments"
              Binding="{Binding Path=Comments}">
                 </dg:DataGridTextColumn>
             </dg:DataGrid.Columns>
           </dg:DataGrid> 

On the datagrid SelectionChanged event handler I processed the update:

Private Sub MyDataGrid_SelectionChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles MyDataGrid.SelectionChanged
     
        Using dtChanges As TestTableDataTable = CType(dsWHOEMR_DEV.TestTable.GetChanges, Entities.WHOEMR_DEVDataSet.TestTableDataTable)

            If Not dtChanges Is Nothing Then
                    Using ta As New TestTableTableAdapter
                    If ta.Update(dtChanges) > 0 Then
                        dsWHOEMR_DEV.Merge(dtChanges)
                        dsWHOEMR_DEV.AcceptChanges()
                    Else
                        Debug.WriteLine("row NOT updated")
                    End If
                End Using
            End If
        End Using
         End Sub


I tried to do a bind in code this way:

Dim myBinding As New Binding  
   'table in typed dataset that contains data I want to display 
myBinding.Source=DAL.ObjectFactory.GetDataset("PatIDDataset1").TestTable  
    'column from dataset table I want to bind to and display in my grid 
myBinding.Path = New System.Windows.PropertyPath("PatID")  
Dim NewColumn As New Microsoft.Windows.Controls.DataGridTextColumn  
NewColumn.Binding = myBinding  
NewColumn.Header = "PatID"  
Me.MyDataGrid.Columns.Add(NewColumn)  



Nothing displayed in the grid other than the column header. 

Has anyone been able to do this kind of binding successfully? 

Coordinator
Feb 18, 2009 at 12:24 PM
You have to set the source binding on the DataGrid.ItemsSource and for the column you just need to set the path.