0
votes

Not sure if this question has been asked before, so here goes.. I have a front end app coded in C# windows forms. On a second form i have two datagridviews that gets populated from two different sql server pre-defined views

I need to refresh both datagrids at the same time with a single button click My button click even looks like this..

private void RefreshBTN_Click(object sender, EventArgs e)
    {
        SqlConnection myConnection = new SqlConnection("removed for illustration only");
        string query = "select * from daily_orders order by orderno DESC";
        SqlCommand cmd = new SqlCommand(query, myConnection);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);
        dataGridView1.DataSource = dt;
    } 

How i understand this is, C# opens new connection, queries the DB and returns by filling datagridview1 with the required data. I would like the same click event to request data from another sql view and populate another datagridview at the same time. Visually both grids are aligned vertically on the same form, one on to of the other.

Many thanks in advance

1
Why don't you try using datagridview1.update(); or datagridview1.refresh(); - Microsoft DN

1 Answers

1
votes

Move the code for refreshing Grid1 into a separate function. Then copy paste and duplicate that function for Grid2. Change the SQL for Grid2 as well as the Grid2 name. Rename the copied function with 2. Then add a call to both functions so your button click will refresh both grids.

private void RefreshBTN_Click(object sender, EventArgs e)
{
    //call both functions to refresh both on button click
    RefreshGrid1();
    RefreshGrid2();
}

private void RefreshGrid1()
{
    SqlConnection myConnection = new SqlConnection("removed for illustration only");
    string query = "select * from daily_orders order by orderno DESC";
    SqlCommand cmd = new SqlCommand(query, myConnection);
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    da.Fill(dt);
    dataGridView1.DataSource = dt;
}

//give this function a unique name to represent the second grid refresh
private void RefreshGrid2()
{
    SqlConnection myConnection = new SqlConnection("removed for illustration only");
    string query = "select * from daily_orders order by orderno DESC";
    SqlCommand cmd = new SqlCommand(query, myConnection);
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    da.Fill(dt);
    //rename this to your second grid name
    dataGridView2.DataSource = dt;
}