multi-threading question

sde

Centurion
Joined
Aug 28, 2003
Messages
160
Location
us.ca.fullerton
I have a search form with a textbox, button, and a datagrid.

when the user submits a search, it calls on a .dll which queries a very large database.

i want to use asynchronous threads for the search, and have the new thread populate my datagrid.

Code:
...
using My.Customer.Class
using System.Data;
using System.threading;

...
  private DataSet ds = new DataSet();
  private Customer cust = new Customer();

  private void btnSearch_Click(object sender, System.EventArgs e)
  {
    ThreadStart entryPoint = new ThreadStart(SetDG);
    Thread searchThread =	new Thread(entryPoint);
    searchThread.Name = "Customer Search";
    searchThread.Start();
  }

  private void SetDG()
  {
    // Customer.SearchLastname() returns a dataset
    ds = cust.SearchLastName(txtSearch.Text.ToUpper());
    dataGrid1.SetDataBinding(ds,"Customers");
  }
...

Below is the exception generated. Any insight would be greatly appreciated.
System.ArgumentException: Controls created on one thread cannot be parented to a control on a different thread.
at System.Windows.Forms.ControlCollection.Add(Control value)
at System.Windows.Forms.DataGridTextBoxColumn.SetDataGridInColumn(DataGrid value)
at System.Windows.Forms.DataGridColumnStyle.SetDataGridTableInColumn(DataGridTableStyle value, Boolean force)
at System.Windows.Forms.GridColumnStylesCollection.AddDefaultColumn(DataGridColumnStyle column)
at System.Windows.Forms.DataGridTableStyle.SetGridColumnStylesCollection(CurrencyManager listManager)
at System.Windows.Forms.DataGrid.PairTableStylesAndGridColumns(CurrencyManager lm, DataGridTableStyle gridTable, Boolean forceColumnCreation)
at System.Windows.Forms.DataGrid.SetDataGridTable(DataGridTableStyle newTable, Boolean forceColumnCreation)
at System.Windows.Forms.DataGrid.Set_ListManager(Object newDataSource, String newDataMember, Boolean force, Boolean forceColumnCreation)
at System.Windows.Forms.DataGrid.Set_ListManager(Object newDataSource, String newDataMember, Boolean force)
at System.Windows.Forms.DataGrid.SetDataBinding(Object dataSource, String dataMember)
at RUS.Form1.SetDG() in c:\visual studio projects\customer-test\form1.cs:line 183
 
// update

when i use
Code:
dataGrid1.DataSource = ds;
instead of SetDataBinding() , it will load the grid the first time. however when i run another search, i get the same exception as above.
 
You may need to have a look at moving your function SetDG into a new class and having a callback from that class to the parent thread. A good example that I have got some great ideas from is at http://abstractvb.com/code.asp?A=1027.

I think you could change the sub ThreadCompleted in the example above to include your dataset ds as a passed variable such that when it completes the job in the new thread it passes that back to the main thread so that you can populate your datagrid. Let me know how you get on.
 
Back
Top