I have database with a product_list table
+----+-------------+-------+-------+
| id | description | price | Stock |
+----+-------------+-------+-------+
| 1 | Item 1 | 1.50 | 5 |
+----+-------------+-------+-------+
Then I have a two windows form application. Each application is on separate project.
- First application is to insert a data to the table which has a query of
INSERT INTO product_list (description, price, stock) VALUES ('Item 2', 2.00, 10)
. - Second application is to view the table in real time using datagridview. i have a object for my database and have a function name GetTable() that return a DataTable.
Here's the code for the database object that return a DataTable.
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;
}
Here the code for the multithreading
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() {
while (true) {
testTable = inventoryDB.GetTable();
this.dataGridView1.DataSource = testTable;
this.dataGridView1.Update();
this.dataGridView1.Refresh();
}
}
when i run visual studio give a InvalidOperationException.