简体   繁体   中英

Update datagridview row from a thread in c#

I have a datagridview on a windows form application.

Application post all displayed data to an external website. website return codes so application detrmine status of posted data.

I need to create a parametrized thread that take row index as parameter and post the row data and update it by return value. (It may involve changing row background color and changing a columns value)

Is it possible the way i think? or there is a better way?

Well, since the DataGridView is a GUI control, you will not be able to make changes to it from another thread. You will have to send a message to the main GUI thread. Fortunately, C# has good support for this. Write a method (presumably in your main form class) which does the actual work:

public void SetRowFromWebResult(int row, Color background, ...)
{
    // ...
}

Then, within your thread, use the Invoke method on the form object (not the delegate):

myForm.Invoke(() => myForm.SetRowFromWebResult(row, background, ...));

So presumably you would run your HTTP request in a thread like this:

int row = ...;
var myThread = new Thread(() =>
{
    // Fire off the request
    var request = WebRequest.Create(...);
    var response = ...;

    // Calculate the parameters (e.g. row background color)
    Color background = (response.Code == ...) ? ... : ...;

    // Tell the GUI to update the DataGridView
    myForm.Invoke(() => myForm.SetRowFromWebResult(row, background, ...));
});
myThread.Start();

Aditionally you can use a background worker thread in order to prevent a cross thread exception.

Regards

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