如何刷新DataGridView?

时间:2014-05-28 08:21:18

标签: c# datagridview

我正在尝试强制DataGrid在表单关闭事件上刷新其内容。我尝试了各种方法,在这个论坛上搜索了答案,但我仍无法找到解决方案。

这是我的DataGridView的填充方式:

string strCon = ConfigurationManager.ConnectionStrings["ST"].ConnectionString.ToString();
string strSQL = "SQL QUERY";
SqlDataAdapter dataAdapter = new SqlDataAdapter(strSQL, strCon);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
bindingSource1.DataSource = table;
dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = bindingSource1;

我已经尝试了Invalidate方法,BindingSource.ResetBindings,但GridView仍然没有刷新。如何强制刷新它?

3 个答案:

答案 0 :(得分:0)

数据刷新

我认为你在谈论数据刷新。在这种情况下,您只需重新绑定您的DatagridView到源:

DataGridView dataGridView1 = new DataGridView();
dataGridView1.DataSource = aDataSource;

//Update Data in aDataSource
//...

dataGridView1 = null;
dataGridView1.DataSource = aDataSource;

在您的代码中,快照aDataSource实际上应该是bindingSource1。正如@ GIVE-ME-CHICKEN所提到的那样,在你的情况下,你应该将重新绑定包含在正确的回调中,以将它附加到正确的事件中:

 private void Form1_FormClosing(object sender, FormClosingEventArgs e){ ... }

数据刷新

如果您不想重新绑定源代码,可以采用其他解决方案:将dataGridView1绑定到Collection Observable 。在这种情况下,只需实现 INotifyCollectionChanged 接口即可将更改通知给其侦听器(您的DataGridView组件)

图形刷新

如果您只搜索图形刷新,则有一种特定的方法:

dataGridView1.Refresh();

答案 1 :(得分:0)

您可以尝试更改此行:

bindingSource1.DataSource = table;

bindingSource1.DataSource = table.DefaultView;

答案 2 :(得分:0)

也许这样做会有所帮助?

public DataTable GetData(string SQLQuery)
{
   string strCon = ConfigurationManager.ConnectionStrings["ST"].ConnectionString.ToString();
   string strSQL = "SQL QUERY";
   SqlDataAdapter dataAdapter = new SqlDataAdapter(strSQL, strCon);
   SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
   DataTable table = new DataTable();
   table.Locale = System.Globalization.CultureInfo.InvariantCulture;
   dataAdapter.Fill(table);
}

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
   //Maybe only one of the clear code works.
   dataGridView1.Rows.Clear();
   dataGridView1.DataSource = null; 

   BindingSource bindingSource1 = new BindingSource();
   bindingSource1.DataSource = GetData("SQL QUERY");
   dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
   dataGridView1.ReadOnly = true; //<-----------Try taking this off aswell
   dataGridView1.DataSource = bindingSource1;
}