Fill dataGrid from MySQL database in C# WPF
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;