0

Hi everyone I have a DataGridView, inside of it is 2 columns, FullName and VoteCount. I want to refresh the DataGridView, for changes in my Database. How do I refresh the DatagridView without closing the form or clicking any button? Is it possible?

Here's my code :

    private void President()
    {
        sc.Open();
        cmd = new SqlCommand("SELECT (LastName + ', ' + FirstName + ' ' + MiddleName) as FullName,Vcount as VoteCount FROM TableVote WHERE Position='President'", sc);

        try
        {
            _da = new SqlDataAdapter();
            _da.SelectCommand = cmd;
            DataTable _dt = new DataTable();
            _da.Fill(_dt);
            BindingSource bs = new BindingSource();
            bs.DataSource = _dt;
            PresDG.DataSource = bs;
            _da.Update(_dt);

            PresDG.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            PresDG.Columns["FullName"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            PresDG.Columns["VoteCount"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            PresDG.Columns["VoteCount"].Width = (100);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            sc.Close();
        }
    }
4

6 回答 6

1

当您想刷新数据时调用此函数。

YourGrid.DataSource = Refresh("SELECT...");

private BindingSource Refresh(string sql)
{
    try
    {
        using (var da = new SqlDataAdapter(sql, new SqlConnection(Properties.Settings.Default.ConnectionString)) { FillLoadOption = LoadOption.Upsert })
        {
            da.SelectCommand.Connection.Open();
            da.Fill(dataSet.YourTable);
        }
    }
    catch(Exception ex) { MessageBox.Show(ex.Message); }

    return new BindingSource(dataSet, "YourTable");
}
于 2013-10-29T07:54:17.153 回答
1

我认为您必须重新填充完整的 DataGridView。

方法:

  1. 您可以在给定的时间间隔内使用 Microsoft Tick-Class
  2. 您使用 Microsoft Tick-Class 检查数据库中的更改。如果有一些更改,请重新填充完整的 DataGridView。
于 2013-10-29T07:16:25.530 回答
0

使用计时器并执行此操作

string connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";

MySqlConnection conn = new MySqlConnection(connectionString);
MySqlDataAdapter adptr = new MySqlDataAdapter("Select * FROM " + tableName, conn);
DataTable tabloSql = new DataTable();
adptr.Fill(tabloSql);
dataGridView1.DataSource = tabloSql;

注意:如果您的程序未对 DataTable 进行更改,请执行此操作。如果在您刷新表格时对数据表进行更改,您对数据表的更改将被删除

于 2013-10-29T07:51:57.457 回答
0

您的数据库是否经常更新?如果是这样,您可以使用计时器进行定期更新。

于 2013-10-29T07:19:33.977 回答
0

您可以使用 Sql server CLR 集成。 这里 这里

稍作阅读后,我将发布更多详细信息,但是我希望它可以为您提供指导,或者您可能会找到解决方案。

更新 您可以创建一个触发器应用程序并使用该触发器应用程序来调用您的绑定 gridview 方法。 是编写触发器并实现它的一个很好的例子。

CLR SP

于 2013-10-29T07:34:39.383 回答
0

有两种情况:

  • 如果您经常刷新 datagridview,您可以设置一个计时器来更新结果。
  • 如果在插入或更新操作后刷新,则在操作结束时调用您的绑定方法。
于 2013-10-29T07:36:37.690 回答