简体   繁体   中英

How to add a row and change cell value in DataGridView from a different thread?

I am using a DataGridView table in my windows form.
I want to add new row and change the cell values of the same row from inside a thread repeatedly.

Now I know how to use Invoke function to change text of a control.
For example:

public void SetControlText(Control control, string text)
{
  if (this.InvokeRequired)
  {
    this.Invoke(new Action<Control, string>(SetControlText), new object[] { control, text });
  }
  else
  {
    control.Text = text;
  }
}

However, I can't figure out how to do this for DataGridView .

It does work exactly the same way, eg:

public void SetCellText(DataGridView control, int x, int y, string text)
{
    if (this.InvokeRequired)
    {
        this.Invoke(() => SetCellText(control, x, y, text));
    }
    else
    {
        control[x, y] = text;
    }
}

I only changed the Invoke call to use a lambda action - I like it more that way, but your way would also work...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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