[英]C# Updating a DataGridView/DataSource from MySQL
I'm writing a program that updates user accounts on a MySQL database. 我正在编写一个更新MySQL数据库用户帐户的程序。 The program is going to be used on multiple computers at once.
该程序将同时在多台计算机上使用。
Currently I load the MySQL data into a DGV by this and refresh in a similar way; 目前我通过它将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
and when editing I get the DGV row to a DataRow, and then update the DGV by changing the DataRow like this (from another form); 编辑时,我将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;
My problem is, I want to update the DGV with any new/modified rows from the MySQL database every xx seconds, and if modifying a row when this happens the DataRow is then Invalid as the above code re-makes the whole structure. 我的问题是,我想每隔xx秒用MySQL数据库中的任何新的/修改的行更新DGV,如果在发生这种情况时修改了一行,那么DataRow就是无效的,因为上面的代码重新构成了整个结构。
Is there a way to update the DGV or DGV DataSource and maintain the ability to use the DataRow I pulled for editing? 有没有办法更新DGV或DGV数据源并保持使用我提取的DataRow进行编辑的能力? How can I update the Datasource with any changes from the MySQL database.
如何使用MySQL数据库中的任何更改来更新数据源。
I have tried BindingSource and a whole bunch of other things I have googled. 我尝试过BindingSource和其他一些我用Google搜索过的东西。
I could find UserID in the DGV then update the row that way, if no answer is found here. 如果在这里找不到答案,我可以在DGV中找到UserID,然后以这种方式更新行。
Currently when editing a user, if the DGV refreshes with the SQL Database my edit form will not update the DGV as the DataRow no longer exists where it was. 目前,在编辑用户时,如果DGV使用SQL数据库刷新,我的编辑表单将不会更新DGV,因为DataRow不再存在。
This is what I am using, works nicely. 这就是我正在使用的,工作得很好。 Only gets the rows that have been updated since we last checked.
仅获取自上次检查以来已更新的行。 Still using the example in the question to retrieve the Database initially
仍然使用问题中的示例来初始检索数据库
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.