0

i´m a beginner in C#,

a start a new Thread

pollprintthread = new System.Threading.Thread(PollPrint);
pollprintthread.Start();

in this Thread i call a function with a Datagridview

void PollPrint()
{
    (some code)
    printausfueren();
    (some code)
}

public void printausfueren()
{
    (some Code)
    object[] row = { sqlReader[0], sqlReader[1], sqlReader[3], sqlReader[2], sqlReader[4], sqlReader[5], sqlReader[6], sqlReader[7] };
    dataGridViewPrint.Rows.Add(row);
    (some Code)
}

but i can´t use printausfuheren().invoke, i found any tutorials but only for Static Methods

Please Help :)

Markus
  • 20,838
  • 4
  • 31
  • 55
ovonel
  • 9
  • 1

2 Answers2

2

You can find a good explanation here: https://stackoverflow.com/a/12179408/67038

However, I would recommend that you wrap your call to dataGridViewPrint.Rows.Add in a method and call that method instead.

You will want to do this because there may be other actions that you wish to take on the UI when you add those rows.

For example, if you are adding a lot of rows, you are going to want to call BeginEdit/EndEdit on the grid, so that it does not try to repaint itself for every row that you add:

public void printausfueren()
{
    //(some Code)
    object[] rows = { sqlReader[0], sqlReader[1], sqlReader[3], sqlReader[2], sqlReader[4], sqlReader[5], sqlReader[6], sqlReader[7] };
    dataGridViewPrint.Invoke(new Action(() => LoadGrid(rows)));
    //(some Code)
}

private void LoadGrid(object[] rows)
{
    // only need BeginEdit/EndEdit if you are adding many rows at a time
    dataGridViewPrint.BeginEdit(false);
    dataGridViewPrint.Rows.Add(rows);
    dataGridViewPrint.EndEdit();
}
Community
  • 1
  • 1
JMarsch
  • 21,484
  • 15
  • 77
  • 125
0

You can easily use anonymous methods to do complex invokes, such as:

yourForm.Invoke( (MethodInvoker) delegate() { dataGridViewPrint.Rows.Add(row); } );

This will auto-magically capture the row instance etc.

Luaan
  • 62,244
  • 7
  • 97
  • 116
  • This code won't compile (I wish it would). You get this: "Cannot convert lambda expression to type 'System.Delegate' because it is not a delegate type". Unfortunately, you have to make the syntax a little choppier: http://stackoverflow.com/a/2367763/67038 – JMarsch Jan 07 '14 at 15:08
  • 1
    @JMarsch I've updated the answer the easiest way that works :) – Luaan Jan 07 '14 at 15:26