WPF Datagrid and Binding?

Sarah Reynolds

Sarah Reynolds

Feb 6 2012 6:26 PM

I'm learning c# at the moment and have decided to look into WPF but I'm having a real mare!!

In my standard winforms apps I can populate a datagridview with the following code:

DBConnect DBConPL = new DBConnect();
string strSqlPL = "SELECT name AS 'Product Name', SUM(quantity) AS 'QTY' FROM order_product WHERE order_id IN (" + idString + ") GROUP BY name"; 

BindingSource bSourcePL = new BindingSource();
bSourcePL.DataSource = DBConPL.GetData(strSqlPL);

dataGridView1.DataSource = bSourcePL;

Unfortunately, I just cannot get anything similar using WPF.  I have tried:

DataTable dt = new DataTable();
MySqlDataAdapter dap = new MySqlDataAdapter(strSql, connection);

if (OpenConnection() == true)

dataGrid1.DataContext = dt.DefaultView;

But the datagrid just shows 1 empty row and no column headers. I'm not sure if I also need to edit the properties in design view or edit the xaml.

My xaml is:

<DataGrid AutoGenerateColumns="true" Height="102" HorizontalAlignment="Left" Margin="16,115,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="245" ItemsSource="{Binding}" />

Can anyone please, please point me in the right direction before I pull the rest of my hair out!?

Many thanks

Answers (2)