That you do it using DataTable, and the DataGridView without defined columns
private void button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("Nombre");
dt.Columns.Add("Apellido");
dt.Rows.Add(new object[] { "Clint", "Eastwood" });
dt.Rows.Add(new object[] { "Leo", "Messi" });
this.dataGridView1.DataSource = dt;
}
private void button2_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("Id");
dt.Columns.Add("Correo");
dt.Columns.Add("Teléfono");
dt.Rows.Add(new object[] { 1, "[email protected]", "342245252" });
dt.Rows.Add(new object[] { 2, "[email protected]", "24523466" });
this.dataGridView1.DataSource = dt;
}
In the previous example I create the columns in the DataTables but you can fill it directly with a query with SqlDataReader
DataTable dt = new DataTable();
SqlCommand command = new SqlCommand("SELECT * FROM TABLA", conn);
using (SqlDataReader reader = command.ExecuteReader())
{
dt.Load(reader);
reader.Close();
}