Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill dataGrid from MySQL database in C# WPF

I want to fill a dataGrid in my WPF application.

My XAML:

<DataGrid AutoGenerateColumns="True" Height="200" HorizontalAlignment="Left" 
Margin="102,72,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="848" />

My code behind:

  public void FillGrid()
    {
        string MyConString =    
        "SERVER=myserver.com;" +
        "DATABASE=mydatabase;" +
        "UID=myuserid;" +
        "PASSWORD=mypass;";

        string sql = "SELECT clientnr, name, address FROM clients ORDER BY name";

        MySqlConnection connection = new MySqlConnection(MyConString);
        MySqlCommand cmdSel = new MySqlCommand(sql, connection);
        DataTable dt = new DataTable();
        MySqlDataAdapter da = new MySqlDataAdapter(cmdSel);
        da.Fill(dt);
        dataGrid1.DataContext = dt;
    }

I'm sure that the MySQL part is correct, it does not give any errors. VS10 express doesn't give any errors. But if i execute the method my dataGrid won't be filled.

What I'm doing wrong?

Thanks in advance!

like image 594
Lars Boele Avatar asked Jun 06 '11 16:06

Lars Boele


1 Answers

Set your DataGrid's binding:

<DataGrid ItemsSource="{Binding }" />
like image 123
Rachel Avatar answered Sep 26 '22 19:09

Rachel