如何在c#中创建用于访问datagridview控件的委托方法?

如何在c#中创建用于访问datagridview控件的委托方法?,c#,.net,winforms,C#,.net,Winforms,我有一个winForm,其中我使用BackGroundWorker控件保持窗体GUI活动。 现在我从backgroundworker\u doWork()方法访问datagridview,因此我在下面创建了一个委托方法: delegate void updateGridDelegate(); private void invokeGridControls() { if (autoGridView.InvokeRequired) {

我有一个winForm,其中我使用
BackGroundWorker
控件保持窗体GUI活动。 现在我从
backgroundworker\u doWork()
方法访问datagridview,因此我在下面创建了一个委托方法:

    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
        }
    }
backgroundworker\u DoWork()
事件中,m访问datagridview作为

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
尝试使用动作代理 假设您使用的是.NET2.0及更高版本

 autoGridView.Invoke(
            new Action(
                delegate()
                {
                    int temp2noofrows = autoGridView.Rows.Count - 1;// 
                }
        )
        );

像这样的问题是,您需要一个非常特定的更新方法来运行委托。例如,更新文本框中的文本

创建与先前定义的方法具有相同签名的委托:

public delegate void UpdateTextCallback(string text);
在线程中,您可以在文本框上调用Invoke方法,传递要调用的委托以及参数

myTextBox.Invoke(new UpdateTextCallback(this.UpdateText), 
            new object[]{"Text generated on non-UI thread."});
这就是运行代码的实际方法

// Updates the textbox text.
private void UpdateText(string text)
{
  // Set the textbox text.
  myTextBox.Text = text;
}
注意:不要创建与EventHandler委托签名匹配的方法并传递该签名。如果委托的类型为EventHandler,则控件类上的Invoke实现将不考虑传递给Invoke的参数。它将传递为sender参数调用调用的控件以及为e参数传递EventArgs.Empty返回的值


因此,在你的情况下,你需要确保你传递了更新网格所需的所有信息。

@foustz:如果这个答案解决了你的问题,请接受这个答案:),我的朋友