【问题标题】:How to add a row and change cell value in DataGridView from a different thread?如何从不同的线程添加一行并更改 DataGridView 中的单元格值?
【发布时间】:2014-09-15 11:46:15
【问题描述】:

我在 Windows 窗体中使用DataGridView 表。
我想添加新行并重复从线程内部更改同一行的单元格值。

现在我知道如何使用Invoke 函数来更改控件的文本了。
例如:

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;
  }
}

但是,我不知道如何为 DataGridView 执行此操作。

【问题讨论】:

    标签: c# multithreading winforms datagridview


    【解决方案1】:

    它的工作方式完全相同,例如:

    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;
        }
    }
    

    我只更改了Invoke 调用以使用 lambda 操作 - 我更喜欢这种方式,但你的方式也可以......

    【讨论】:

    • 如果我使用 lambda 表达式,我必须让它委托,否则会抛出错误Cannot convert lambda expression to System.Delegate
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多