0

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

Adam
  • 482
  • 1
  • 8
  • 18
  • possible dupe? https://stackoverflow.com/questions/142003/cross-thread-operation – Jasen Jul 07 '18 at 12:21
  • Not possible it's a duplicate @Jasen all C# GUI controls are not multi threaded safe and require a `MethodInvoker` like the duplicate says – Raymond Nijland Jul 07 '18 at 12:34
  • @RaymondNijland I'm not familiar with method invokers, could you please elaborate more. I have looked at the linked material and still dont quite understand what I'm supposed to do. Also, do you know why it works inside a button event and not the trigger function? – Adam Jul 07 '18 at 17:38
  • you should read the other post and comment on the answers there if they are unclear. – Jasen Jul 08 '18 at 06:56

0 Answers0