g752042
g752042

Reputation: 31

Binding data from SQLite to DataGrid using C# and WPF

I have a method Load in MyController:

public void Load(ItemsControl control, string commandText)
{
    try
    {
        _db.OpenConnection();

        using (SQLiteCommand command = new SQLiteCommand(commandText, _db.Connection))
        using (SQLiteDataAdapter dataAdapter = new SQLiteDataAdapter(command))
        {
            DataTable dataTable = new DataTable();
            dataAdapter.Fill(dataTable);
            control.ItemsSource = dataTable.AsDataView();
        }
    }
    catch (Exception exp)
    {
        //...;
    }
}

Then in XAML I have:

<DataGrid x:Name="DataGrid_1" ... AutoGenerateColumns="True" Loaded="DataGrid_1_Loaded">

and finally in DataGrid_1_Loaded() I'm calling the method Load() like this:

MyController.Load(DataGrid_1, "CREATE VIEW IF NOT EXISTS content_for_dg AS SELECT name,surname FROM people");

When I run the program, I see a little white space at the top of Data_Grid_1 but no columns and no data. I opened the database with SQLite Browser and the view content_for_dg exists and contains correct data...

What am I missing ? Why the data are not shown in DataGrid ?

Upvotes: 1

Views: 1998

Answers (1)

g752042
g752042

Reputation: 31

If I remove using (SQLiteCommand command = new SQLiteCommand(commandText, _db.Connection)) and create SQLiteDataAdapter this way SQLiteDataAdapter dataAdapter = new SQLiteDataAdapter(commandText, _db.Connection), then it works fine...

public void Load(ItemsControl control, string commandText)
{
    try
    {
        _db.OpenConnection();

        using (SQLiteDataAdapter dataAdapter = new SQLiteDataAdapter(commandText, _db.Connection))
        {
            DataTable dataTable = new DataTable();
            dataAdapter.Fill(dataTable);
            control.ItemsSource = dataTable.AsDataView();
        }
    }
    catch (Exception exp)
    {
        //...;
    }
}

Upvotes: 1

Related Questions