I'm new in WPF and I'd like to visualize data from SQL query to WPF DataGrid. I have problem with a how correctly bind a data:
SqlCommand cmd = new SqlCommand(sql_dotaz, conn);
InfoText.Text += ("Příkaz vytvořen a připojen" + "\n");
try
{
conn.Open();
InfoText.Text += ("Připojení otevřeno" + "\n");
SqlDataReader reader = cmd.ExecuteReader();
int row_count = reader.FieldCount;
ArrayList propoj = new ArrayList();
for (int i = 0; i < row_count; i++)
{
propoj.Add(reader.GetName(i));
tabView.Columns.Add(new DataGridTextColumn
{
Header = reader.GetName(i),
Binding = new Binding(reader.GetName(i))
});
//Here is the problem!!!
tabView.Items.Add(new {propoj[i] = "Hello"});
}
Problem is when a try to add a new item, it's throws an error. I cannot explicitly set the header name like this (Invitation = "Hello").
I also tried
tabView.Columns.Add(new DataGridTextColumn
{
Header = reader.GetName(i),
Binding = new Binding(reader.GetName(i))
});
string record = reader.GetName(i));
tabView.Items.Add(new {record = "Hello"});
But there is still a problem with the header name - The DataGrid is empty.
Please let me know if you have any ideas. Thanks a lot!
In the I find the solution. Maybe it´s not best but it´s work. I create DataSet and SQL Adapter
adapter.Fill(dSet);
this.DataContext = dSet.Tables[0].DefaultView;
and in XAML:
<DataGrid Height="Auto" Width="Auto" Name="tabView3" ItemsSource="{Binding}" />
And now it´s work fine :-)