Add row to DataTable bound with DataGrid in other thread

M

MiSo

Hi,
I add rows to DataTable bound to DataGrid.
Function which is adding the data is called from other thread.
Data asychronicaly comes from RS232, and I add this data to Datatable. After
this operations Windows Forms not responding.?

To try to solve this problem I prepare another simple test aplication.
This application adds rows to datatable also but once with button click and
twice after button click function is called from separate thread.
Part of code:

private void addtodb()
{
// ADD ROWS TO DATABASE
dst._TableRow r;
r = (dst._TableRow) ds._Table.NewRow();
r.id_ctrl = 1;
r.id_data = 1;
ds._Table.Rows.Add(r);
}

private void bt1_Click(object sender, System.EventArgs e)
{
Thread t = new Thread(new ThreadStart(this.addtodb));
t.Start();
}

private void bt2_Click(object sender, System.EventArgs e)
{
addtodb();
}

And where is the problem?
When I add rows in button event handler (bt1_Click) that OK.
When I add rows in separate thread (bt1_Click) than when number of rows exceded
grid size than vertical bars are not on the right place.
You can see the efect here: http://www.sic.pl/gridtest

Mirek
 
M

Miha Markic [MVP C#]

Hi,

Never ever tough UI controls from within non UI-thread That includes
manipulating DataTable that is bound, too.
You might consider using Invoke method to fire method addtodb from within UI
thread.
 
M

MiSO

User said:
Hi,

Never ever tough UI controls from within non UI-thread That includes
manipulating DataTable that is bound, too.
You might consider using Invoke method to fire method addtodb from within UI
thread.
It's working. Wonderfull.
Thx.

I've looked out in MSDN and I've found note:
Note There are four methods on a control that are safe to call from
any thread: Invoke, BeginInvoke, EndInvoke, and CreateGraphics. For all
other method calls, you should use one of the invoke methods to marshal
the call to the control's thread.

I hope that this solve my second problem with RS232 thread too
Mirek
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top