Binding dynamic query to DataGrid C# WPF

1.1k Views Asked by At

Is it possible to bind a query to a Data Grid without specifying the table or columns?

Let's say I have this query:

string query = "select PersonName from Persons'

but it changes and next time I have:

string query = "select Email from Persons'

I'm using Sqlite Net extension, and I have problems binding without specifying table object explicitely, for example:

listPerson.DataContext = db.Query....
2

There are 2 best solutions below

1
On

Yes, you can bind any table or columns to datagrid dynamically. first in xaml code verify your columns :

<DataGrid x:Name="dataGrid" > 
     <DataGrid.Columns>
            <DataGridTextColumn Header="col1" Binding="{Binding col1}">
            <DataGridTextColumn Header="col2" Binding="{Binding col2}">
     </DataGrid.Columns>
</DataGrid>

after xaml code you in code behind bind data

      private void FillDataGrid()
    {
        var query = Context.Database.SqlQuery<Table>("Select * From table");

        var result = query.ToList();
        dataGrid.ItemsSource = result ;
    }
0
On

Let me explain my problem a little bit more.

I want to do some sort of dynamics reports. I use SQLite database with SQLite NET extension. I load query from xml file (this query can be anything from database). I want to load somehow result of this query to grid or listview. Usually it'not problem because I "mapped" my data to an objects in model for example:

 using (var db = new SQLiteConnection(new SQLite.Net.Platform.Generic.SQLitePlatformGeneric(), "zakupy.db"))
        {
            listPerson = db.Table<Persons>().Where(x => x.Property == "P" && x.Status == 0).ToList();
        } 
lstPersons.DataContext = listPerson;

Now I tried to do something like this:

  using (var db = new SQLiteConnection(new SQLite.Net.Platform.Generic.SQLitePlatformGeneric(), "zakupy.db"))
        {
            var cc = db.Query<Table>("SELECT * from Events");
            lstPersons.DataContext = cc.ToList();
        }

But in grid I only see something like this: enter image description here