简体   繁体   English

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

[英]Fill dataGrid from MySQL database in C# WPF

I want to fill a dataGrid in my WPF application.我想在我的 WPF 应用程序中填充一个 dataGrid。

My XAML:我的 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.我确信 MySQL 部分是正确的,它不会给出任何错误。 VS10 express doesn't give any errors. VS10 express 没有给出任何错误。 But if i execute the method my dataGrid won't be filled.但是,如果我执行该方法,我的 dataGrid 将不会被填充。

What I'm doing wrong?我做错了什么?

Thanks in advance!提前致谢!

Set your DataGrid's binding:设置 DataGrid 的绑定:

<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).正如 Rachel 建议的那样,您肯定希望它绑定到 DataTable 而不是 Adapter(适配器的工作是填充 DataTable)。 Also, it's good to enclose connections and commands in usings to make sure everything is cleaned up, like this:此外,最好将连接和命令包含在 usings 中以确保所有内容都已清理干净,如下所示:

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.只需在后面的代码中的InitializeComponents() FillGrid() I just did that and it runs perfectly .我只是这样做了,它运行完美

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM