C#从MySQL更新DataGridView / DataSource

时间:2019-05-27 07:23:36

标签: c# mysql datagridview datasource

我正在编写一个程序来更新MySQL数据库上的用户帐户。该程序将一次在多台计算机上使用。

目前,我以此将MySQL数据加载到DGV中,并以类似的方式刷新;

mySqlDataAdapter = new MySqlDataAdapter("SELECT * FROM a_Users;", connection); // Query the database
DataSet DS = new DataSet(); // Create new DataSet
mySqlDataAdapter.Fill(DS); // Fill the Dataset with the information gathered above
dataGridView1.DataSource = DS.Tables[0]; // Set the dgv source to the newly created DataSet

在编辑时,我将DGV行放入DataRow,然后通过这样更改DataRow(从另一种形式)来更新DGV;

DataRow dr = (dataGridView1.Rows[SelectedRow].DataBoundItem as DataRowView).Row; // Get the selected row to a new DataRow
dr["Phone Number"] = PhoneNumber_tb.Text;

我的问题是,我想每隔xx秒用MySQL数据库中的任何新行/修改过的行更新DGV,如果在这种情况下修改行,则DataRow无效,因为上面的代码重新构成了整个结构

是否可以更新DGV或DGV数据源并保持使用我拉出的DataRow进行编辑的能力? 如何使用MySQL数据库中的任何更改来更新数据源。

我尝试了BindingSource以及我用谷歌搜索过的其他方法。

如果在此处找不到答案,我可以在DGV中找到UserID,然后以这种方式更新行。

当前,在编辑用户时,如果DGV用SQL数据库刷新,由于DataRow不再存在,因此我的编辑表单将不会更新DGV。

1 个答案:

答案 0 :(得分:0)

这就是我正在使用的,效果很好。 仅获取自上次检查以来已更新的行。仍然使用问题中的示例来初始检索数据库

mySqlDataAdapter = new MySqlDataAdapter("SELECT * FROM a_Users WHERE DTGModified > " + LastUpdated.ToString() + ";", connection); // Query the database
DataTable DT = new DataTable(); // Create new DataSet
mySqlDataAdapter.Fill(DT); // Fill the Dataset with the information gathered above
LastUpdated = DateTime.Now.ToString("yyyyMMddHHmmss"); // Save the time we retrieved the database

foreach (DataRow dr in (dataGridView1.DataSource as DataTable).Rows)
{
    foreach(DataRow DTdr in DT.Rows)
    {
        if (dr["ID"].ToString() != DTdr["ID"].ToString()) continue;

        dr.ItemArray = DTdr.ItemArray;
    }
}
相关问题