My program brings in data from a PostgreSQL database and displays it in a data grid viewer, there is a button that re-runs the method (GetDate();) that gets the data. However when I use the same method with the PostgreSQL Data Trigger with NPGSQL the program crashes. I don't understand why its doing it here but not in the button trigger.
This method is used on load.
private void GetData()
{
// PostgeSQL-style connection string
string connstring = "Server=tsimain;Port=5432;Database=netdb;UserId=postgres;Password=password;";
NpgsqlConnection conn = new NpgsqlConnection(connstring);
conn.Open();
string sql = "/* SQL Statment */"
NpgsqlDataAdapter da = new NpgsqlDataAdapter(sql, conn);
ds.Reset();
da.Fill(ds);
dt = ds.Tables[0];
dataGridView1.DataSource = dt;
conn.Close();
}
Then I use the button trigger to re-run the method
private void ButReload_Click(object sender, EventArgs e)
{
GetData();
}
This works fine.
NpgsqlConnection connListenRun = new NpgsqlConnection("Server=tsimain;Port=5432;Database=racenetdb;UserId=postgres;Password=dragway42;SyncNotification=true;");
try
{
connListenRun.Open();
NpgsqlCommand cmd = new NpgsqlCommand("listen RunLogClient;", connListenRun);
cmd.ExecuteNonQuery();
connListenRun.Notification += new NotificationEventHandler(RunFinishNotification);
}
catch (NpgsqlException ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
//connListen.Close();
}
private void RunFinishNotification(object sender, NpgsqlNotificationEventArgs e)
{
GetData();
}
However this doesn't and gives the error:
System.InvalidOperationException: 'Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on.'
on line:
dataGridView1.DataSource = dt;
Any help would be appreciated