在C#WPF中从MySQL数据库填充dataGrid

时间:2011-06-06 16:27:44

标签: c# mysql wpf database datagrid

我想在我的WPF应用程序中填充dataGrid。

我的XAML:

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

我的代码背后:

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

我确信MySQL部分是正确的,它不会给出任何错误。 VS10 express不会给出任何错误。但是如果我执行方法,我的dataGrid将不会被填充。

我做错了什么?

提前致谢!

4 个答案:

答案 0 :(得分:6)

设置DataGrid的绑定:

<DataGrid ItemsSource="{Binding }" />

答案 1 :(得分:3)

你肯定希望它绑定到DataTable而不是适配器,正如Rachel建议的那样(适配器的工作是填充DataTable)。此外,最好在使用中包含连接和命令,以确保清理所有内容,如下所示:

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();
    }
}

答案 2 :(得分:2)

替换

dataGrid1.DataContext = dt; 

dataGrid1.ItemsSource = dt.DefaultView;

答案 3 :(得分:1)

只需在代码中的FillGrid()之后调用方法InitializeComponents()即可。我刚刚做到了,它运行完美