代码之家  ›  专栏  ›  技术社区  ›  FosterZ

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

  •  1
  • FosterZ  · 技术社区  · 14 年前

    我有一个winForm,在里面 BackGroundWorker 现在我正在访问datagridview backgroundworker_doWork() 方法,因此我在下面创建了委托方法:

        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() 事件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
    
    2 回复  |  直到 14 年前
        1
  •  1
  •   TalentTuner    14 年前

    尝试操作委托

     autoGridView.Invoke(
                new Action(
                    delegate()
                    {
                        int temp2noofrows = autoGridView.Rows.Count - 1;// 
                    }
            )
            );
    
        2
  •  0
  •   jimplode    14 年前

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

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

    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参数的控件以及EventArgs返回的值。对于e参数为空。

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