【问题标题】:Refreshing multiple datagridviews with single button click通过单击按钮刷新多个数据网格视图
【发布时间】:2016-12-14 00:42:57
【问题描述】:

不确定以前是否有人问过这个问题,所以这里是.. 我有一个用 C# windows 窗体编码的前端应用程序。在第二种形式中,我有两个从两个不同的 sql server 预定义视图填充的 datagridviews

我需要通过单击一个按钮同时刷新两个数据网格 我的按钮点击甚至看起来像这样..

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 来返回。我希望相同的单击事件从另一个 sql 视图请求数据并同时填充另一个 datagridview。从视觉上看,两个网格在同一个表单上垂直对齐,一个在另一个上。

在此先感谢

【问题讨论】:

  • 你为什么不尝试使用datagridview1.update();datagridview1.refresh();

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


【解决方案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;
}

【讨论】:

  • 哇!太棒了。我有一个类似的想法,但没有想到将网格刷新事件分成两个独特的功能。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-14
  • 1970-01-01
  • 1970-01-01
  • 2016-03-12
  • 2012-12-31
  • 1970-01-01
  • 2012-11-14
相关资源
最近更新 更多