Add row to DataTable bound with DataGrid in other thread

  • Thread starter Thread starter MiSo
  • Start date Start date
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
 
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.
 
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
 
Back
Top