how to display data from multiple tables to dataGridView

c#, datagridview, mysql

Solution

you need to join two tables and fetch the results as below

using(MySqlConnection connection = new MySqlConnection(MyConnectionString))
using(MySqlCommand cmd = connection.CreateCommand())
{
    connection.Open();
    cmd.CommandText = "SELECT pb.Id, pb.Name, pb.MobileNo, e.email FROM phonebook pb INNER JOIN email e ON e.Id= pb.Id";
    MySqlDataAdapter adap = new MySqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    adap.Fill(ds);
    dataGridView1.DataSource = ds.Tables[0].DefaultView;
}

Problem

I want to display the phonebook and email data in one dataGridView. and the problem is it will only display the email table ``` MySqlConnection connection = new MySqlConnection(MyConnectionString); connection.Open(); try { MySqlCommand cmd = connection.CreateCommand(); cmd.CommandText = "SELECT * FROM phonebook"; cmd.CommandText = "SELECT * FROM email"; MySqlDataAdapter adap = new MySqlDataAdapter(cmd); DataSet ds = new DataSet(); adap.Fill(ds); dataGridView1.DataSource = ds.Tables[0].DefaultView; } catch(Exception ex) { MessageBox.Show(ex.Message); } finally { if (connection.State == ConnectionState.Open) { connection.Clone(); } } ```

Original source