1
votes

What do I need to do to get my WPF DataGrid control to bind to a DataTable object?

I've been suffering over this for several days now. Even when the binding and the query both work correctly, and there is observable data in the table - nothing shows up in the data grid.

My XAML code resembles this:

<Window x:Class="DataGridTest.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:TK="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit"
    Title="Window1" Height="300" Width="300">
        <Grid>
            <TK:DataGrid ItemsSource="{Binding Path=DTUsers}" />
        </Grid>
</Window>

My C# code-behind resembles this:
(DAO is my Data Access Object)

public partial class Window1 : Window
{
    public dao DAO = new dao (ConnectionString) ;
    public System.Data.DataTable DTUsers { get; set; }

    public Window1()
    {
        InitializeComponent();

        if (DAO != null)
            DTUsers = DAO.Query( @"SELECT * FROM users" );
            // Returns a DataTable object containing user records.
            // I have confirmed that this returns my data correctly.
    }
}

I've checked the output, and there are no binding errors.
Why will this compile and run, but won't display any data???

(If you don't know where the DataGrid control is, the WPF Toolkit is available here. Install it, add a reference to WPFToolkit.dll [which will show up in the "Add Reference" dialog under ".NET"], and provide the XML namespace declaration [in my XAML above] to use the WPF DataGrid control.)

1

1 Answers

5
votes

InitializeComponent() will instantiate your markup, including the binding. At that point DTUsers is still null, so nothing is displayed. Then, you change DTUsers, but there's no way for the binding (and therefore the grid) to know that you did it - and so it does not do anything.

You should either make DTUsers a dependency property, or implement INotifyPropertyChanged on your class, and raise PropertyChanged event after you change the value of the property.