简体   繁体   中英

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!

Set your DataGrid's binding:

<DataGrid ItemsSource="{Binding }" />

You definitely want it to be bound to the DataTable and not the Adapter, as Rachel suggested (the adapter's job is to populate the DataTable). Also, it's good to enclose connections and commands in usings to make sure everything is cleaned up, like this:

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";

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

Replace

dataGrid1.DataContext = dt; 

with

dataGrid1.ItemsSource = dt.DefaultView;

Just call the method FillGrid() after InitializeComponents() in your code behind. I just did that and it runs perfectly .

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