简体   繁体   中英

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 ?

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)
    {
        //...;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM