开发者

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 开发者_JS百科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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜