单击按钮即可刷新多个datagridviews

时间:2016-08-08 09:40:21

标签: c# winforms visual-studio datagridview visual-c#-express-2010

不确定此问题是否曾被问过,所以这里就是.. 我有一个用C#windows窗体编码的前端应用程序。在第二个表单上,我有两个datagridviews,它们从两个不同的sql server预定义视图中填充

只需单击一下按钮,我就需要同时刷新两个数据网格 我的按钮点击甚至看起来像..

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;
    } 

我理解这一点,C#打开新连接,查询数据库并通过填充datagridview1返回所需的数据。我希望相同的click事件从另一个sql视图请求数据并同时填充另一个datagridview。在视觉上,两个网格在同一个窗体上垂直对齐,一个在另一个窗格上。

非常感谢提前

1 个答案:

答案 0 :(得分:1)

将用于刷新Grid1的代码移动到单独的函数中。然后复制粘贴并复制Grid2的该功能。更改Grid2的SQL以及Grid2名称。使用2重命名复制的函数。然后添加对两个函数的调用,以便单击按钮将刷新两个网格。

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;
}