Programmatically binding a WPF datagrid to a typed dataset datatable

Feb 3, 2009 at 8: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:

             Binding="{Binding Path=PatID}">
              Binding="{Binding Path=Comments}">

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
                        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 
    '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"  

Nothing displayed in the grid other than the column header. 

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

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