繁体   English   中英

C#从不同的线程填充dataGridView1 CELL

[英]C# Fill dataGridView1 CELL from different thread

我试图从另一个线程调用我的 dataGridView1 但遇到错误,我该如何解决?

谢谢

public void SenddataGridView1(int row, int col, string text)
{
    if (this.dataGridView1.InvokeRequired)
    {
        SetTextCallback h = new SetTextCallback(SenddataGridView1);
        this.Invoke(h, new object[] { row, col, text });
    }
    else
    {
        dataGridView1.Rows[row].Cells[col].Value = text;
    }
}

为了记录,我刚刚测试了这段代码:

private void button1_Click(object sender, EventArgs e)
{
    backgroundWorker1.RunWorkerAsync();
}

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    SetCellValue(0, 0, "Hello World");
}

public void SetCellValue(int columnIndex, int rowIndex, object value)
{
    if (dataGridView1.InvokeRequired)
    {
        dataGridView1.Invoke(new Action<int, int, object>(SetCellValue), columnIndex, rowIndex, value);
    }
    else
    {
        dataGridView1[columnIndex, rowIndex].Value = value;
    }
}

它没有问题。 我没有看到你的代码有什么具体问题——虽然我不知道我在找什么——但我可以保证这段代码有效。

编辑:为了解决您遇到的具体问题,在您提供所有相关信息后就很清楚了,您需要像这样声明您的代表:

public delegate void SetTextCallback(int row, int col, string text);

您只需复制方法声明,更改名称并添加委托关键字。

暂无
暂无

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

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