繁体   English   中英

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

[英]How to create a delegate method for accessing datagridview control in c#?

m具有winForm,并且其中m使用BackGroundWorker控件保持Form GUI处于活动状态。 现在,我从backgroundworker_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_DoWork()事件中以以下方式访问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

尝试使用Action Delegate,并假设您使用的是.net 2.0及更高版本

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

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

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

public delegate void UpdateTextCallback(string text);

在您的线程中,您可以在TextBox上调用Invoke方法,将委托传递给call以及参数。

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,则在Control类上执行Invoke不会考虑传递给Invoke的参数。 它将传递为发件人参数调用Invoke的控件,以及为e参数传递EventArgs.Empty返回的值。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM