shiny
shiny

Reputation: 181

C# Fill dataGridView1 CELL from different thread

I'm trying to invoke my dataGridView1 from another thread but running into errors, How do I fix it?

Thank you

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

Upvotes: 0

Views: 77

Answers (1)

jmcilhinney
jmcilhinney

Reputation: 54457

For the record, I just tested this code:

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

and it worked without issue. I don't see a specific issue with your code - I don't know what I'm looking for though - but I can guarantee that this code works.

EDIT: To address the specific issue you were having, which was clear after you provided all the relevant information, you would need to declare your delegate like so:

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

You just copy the method declaration, change the name and add the delegate keyword.

Upvotes: 1

Related Questions