我有一个带有product_list表的数据库
$code
然后我有两个Windows窗体应用程序。每个应用程序都在单独的项目中。
+----+-------------+-------+-------+
| id | description | price | Stock |
+----+-------------+-------+-------+
| 1 | Item 1 | 1.50 | 5 |
+----+-------------+-------+-------+
。这是返回DataTable的数据库对象的代码。
INSERT INTO product_list (description, price, stock) VALUES ('Item 2', 2.00, 10)
这里是多线程的代码
public DataTable GetTable()
{
DataTable table = new DataTable();
try
{
MySqlDataAdapter daTable = new MySqlDataAdapter(this.query, this.conn);
daTable.Fill(table);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
return table;
}
当我运行visual studio时,会发出InvalidOperationException。
答案 0 :(得分:1)
您可以使用控件的InvokeRequired属性。试试这段代码。
DataTable inventoryTable;
inventoryDB inventoryDB;
Thread updateDataGridView;
public Form1()
{
InitializeComponent();
inventoryDB = new inventoryDB();
}
private void Form1_Load(object sender, EventArgs e)
{
inventoryDB.SetQuery("SELECT id AS ID, description as Description, price as Price, stock as Stock FROM `product_list");
inventoryTable = inventoryDB.GetTable();
this.dataGridView1.DataSource = inventoryTable;
this.updateDataGridView = new Thread(new ThreadStart(this.RealTimeData));
this.updateDataGridView.Start();
}
private void RealTimeData() {
testTable = inventoryDB.GetTable();
this.SetDataSourceInGridView(testTable);
}
// This delegate enables asynchronous calls for setting
// the datasource property on a GridView control.
delegate void GridViewArgReturningVoidDelegate(DataTable testTable);
private void SetDataSourceInGridView(DataTable testTable)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.dataGridView1.InvokeRequired)
{
GridViewArgReturningVoidDelegate d = new StringArgReturningVoidDelegate(SetDataSourceInGridView);
this.Invoke(d, new object[] { testTable });
}
else
{
this.dataGridView1.DataSource = testTable;
this.dataGridView1.Update();
this.dataGridView1.Refresh();
}
}