.net – How to create a delegate method for accessing datagridview control in c#? – Education Career Blog

m having a winForm and in that m using BackGroundWorker control for keeping Form GUI active.
Now i’m accessing datagridview from backgroundworker_doWork() method, so i created a delegate method below:

    delegate void updateGridDelegate();
    private void invokeGridControls()
        if (autoGridView.InvokeRequired)
            updateGridDelegate delegateControl = new    updateGridDelegate(invokeGridControls);
            autoGridView.Invoke(delegateControl);//here i need to do something to access autoGridView.Rows.Count

and in the backgroundworker_DoWork() event m accessing datagridview as

int temp2noofrows = autoGridView.Rows.Count - 1;// here i dn't understand how to call my delegate method, so i can avoid cross threading access error


Try with Action Delegate
and assuming that you are using .net 2.0 and above

            new Action(
                    int temp2noofrows = autoGridView.Rows.Count - 1;// 


The problem you are going to have with things like this is you will need a very specific update method for the delegate to run. For example updating the text in a textbox.

Create a delegate that has the same signature as a method that has been previously defined:

public delegate void UpdateTextCallback(string text);

In your thread, you can call the Invoke method on the TextBox, passing the delegate to call, as well as the parameters.

myTextBox.Invoke(new UpdateTextCallback(this.UpdateText), 
            new object{"Text generated on non-UI thread."});

And this is the actual method that will run your code.

// Updates the textbox text.
private void UpdateText(string text)
  // Set the textbox text.
  myTextBox.Text = text;

Note: Do not create a method that matches the EventHandler delegate signature and pass that. The implementation of Invoke on the Control class will not take into account the parameters passed to Invoke if the type of the delegate is EventHandler. It will pass the control that Invoke was called on for the sender parameter as well as the value returned by EventArgs.Empty for the e parameter.

So in your case you need to make sure you pass in all the information you need in order to update your grid.

Leave a Comment