繁体   English   中英

C#从MySQL更新DataGridView / DataSource

[英]C# Updating a DataGridView/DataSource from MySQL

我正在编写一个更新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;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM