1

getting error in following line "this.dgvReport.Invoke(delegate"

"Cannot convert anonymous method to type 'System.Delegate' because it is not a delegate type"

    public void FillProductGrid()
    {
        ProductSP productSP = new ProductSP();
        DataTable dtbl = new DataTable();
        string productname = "";
        dtbl = productSP.StockReport(productname, this.cbxPrint.Checked);
        this.dgvReport.Invoke(delegate
        {
            this.dgvReport.DataSource = dtbl;
        });
    }
SWeko
  • 30,434
  • 10
  • 71
  • 106
Nisar
  • 5,708
  • 17
  • 68
  • 83

2 Answers2

8

Just add casting to some delegate type with same signature:

this.dgvReport.Invoke((MethodInvoker)(delegate {
        this.dgvReport.DataSource = dtbl;
}));
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
4

The Invoke method has a parameter of type Delegate, and you can only convert an anonymous function to a specific delegate type. You either need to cast the expression, or (my preferred option) use a separate local variable:

// Or MethodInvoker, or whatever delegate you want.
Action action = delegate { this.dgvReport.DataSource = dtbl; };
dgvReport.Invoke(action);

Alternatively, you can create an extension method on Control to special-case a particular delegate, which can make it simpler:

public static void InvokeAction(this Control control, Action action)
{
    control.Invoke(action);
}

Then:

dgvReport.InvokeAction(delegate { dgvReport.DataSource = dtbl; });

Also consider using a lambda expression:

dgvReport.InvokeAction(() => dgvReport.DataSource = dtbl);
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194