Hi All,
I am now developing an application and I need to use thread that will execute functions which will update the datagrid. What that function does is actually checks or monitor whether there is any files in a specified directory that has been changed. If there is then read the all the files in the specified directory again and update a datagrid showing available files in the specified directory.
However I get an exception saying
"Controls created on one thread cannot be parented to a control on a different thread."
I don' know what cause this and how to solve this problem,
This is my code:
private bool changed;
public void MainForm
{
//changed indicate as whether there is any changed to file in folder and then to update datagrid or not
changed = true;//first time read the directory
}
private void MainForm_Load(object sender, System.EventArgs e)
{
monitorFolder();
}
private void updateSharedData()
{
while(true)
{
if(changed)
{
currentSharedFilesDS = getSharedFiles();
//
fillSharedFilesDG(currentSharedFilesDS);
//
changed = false;
}
else
{
Thread.Sleep(new TimeSpan(0, 0, 5, 0, 0));
}
}
}
private void monitorFolder()
{
Thread trd = new Thread(new ThreadStart(updateSharedData));
trd.IsBackground = true;
trd.Start();
}
private void fillSharedFilesDG(DataSet ds)
{
if(ds != null)
{
dgSharedFiles.DataSource = ds;
if(ds.Tables.Count > 0)
dgSharedFiles.DataMember = ds.Tables[0].TableName;
}
}
public DataSet getSharedFilles()
{
//return DataSet contains all the file in the directory
}
I really don't understand what is wrong with this code because I have implemented this code in Java and all are fine.
Hope someone who knows help me to solve this problem.
Thank's

Thread call methods which update datagrid
James Owens
Create a new class and put in the code for filling a datatable.
Make a public event in the new class
before you set the thread and start it, make an instance of the class and add a handler to a local sub for the public event that is in the class.
Then in that sub (which when the event is triggered will send the datatable to this sub) one of the parameters is a datatable.
Set the datagrid to null then to this new datatable
This is the simple way to do it.
Have fun
Joe
gcollins