views:

4583

answers:

1

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.)

+3  A: 

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.

Pavel Minaev
That makes perfect sense! Thanks a ton!
Giffyguy
Hmm --- I moved InitializeComponent() to the very bottom of the constructor, and now at least the DataGrid is able to populate itself with the proper columns and column headers ... but it still shows no data records ... Any other ideas? I'll up-vote you again if you want to give another answer.
Giffyguy
Oh, I had accidentally left my query commented out ... by bad. It works perfectly now, thanks to your answer!
Giffyguy