C# 从 MySQL 更新 DataGridView/DataSource

标签 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 和我在 google 上搜索过的一大堆其他东西。

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

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

最佳答案

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

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

关于C# 从 MySQL 更新 DataGridView/DataSource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56321478/

相关文章:

c# - 通用继承和委托(delegate)

php - 计算重复数据并将其存储到变量中

vb.net - SQLite不能正确存储小数

c# - 刷新数据 GridView 不起作用

c# - 实体做得太多?

c# - 两个输出文件名解析为相同的输出

c# - 节点图编辑器

php - 如何在 Synology 上用 PHP 和 MYSQL 本地连接 MariaDB5?

mysql - 有没有办法从每个查询中获取 2 行?

c# - 无法在 datagridview 中的单元格离开事件中获取当前单元格值