How to show datatable from form 2 in datagridview in form 1

I have a question. I have 2 forms in my project.
In Form 1 I have “search engine” with one textbox and 2 buttons. If you press button1 code takes value from textbox and display search result in datagridview and it works fine. But if you press button2 code will open Form2 and on that form is some sort of “Advanced search” but when I press button1 in Form2 nothing happens on datagridview in Form1.

Code in Form1:

private void button1_Click(object sender, EventArgs e)
{
...
  datagridview1.DataSource = GetDataTable(@"//SQL query", parameters);
...
}

public DataTable GetDataTable(string query, List<SqlParameter> parameters)
    {
        SqlConnection conn = new SqlConnection(connString);
        SqlCommand cmd = new SqlCommand(query, conn);
        cmd.Parameters.AddRange(parameters.ToArray());
        conn.Open();
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);
        conn.Close();
        da.Dispose();
        return dt;
    }
private void button2_Click(object sender, EventArgs e)
    {
        Form2 f2 = new Form2();
        f2.Show();
    }

and code in Form2:

private void button3_Click(object sender, EventArgs e)
{
  ...
    Form1 f1 = new Form1();
    f1.datagridview1.DataSource = f1.GetDataTable(@"//SQL query",parameters);
    this.Close();
}

Thank you in advance!


Source: forms

Leave a Reply