Hi George,
Thanks for your feedback information!
Yes, I think your background information is critical regarding resolving
your problem.
FileSystemWatcher event fires in another thread other than the main GUI
thread, if you add the new row into the DataTable directly, the .Net
Winform databinding code will try to update the new row into the
DataGridView UI.
However, .Net Windows Forms uses the single-threaded apartment (STA) model
because Windows Forms is based on native Win32 windows that are inherently
apartment-threaded. The STA model implies that a window can be created on
any thread, but it cannot switch threads once created, and all function
calls to it must occur on its creation thread. So your code indirectly
manipulates the DataGridView from the non GUI thread which offends the STA
rule in .Net Winform. This may cause some strange and hard to detect
multithreading issue. Please refer to the the article below for more
information:
"Multithreaded Windows Forms Control Sample"
http://msdn.microsoft.com/library/de...us/cpguide/htm
l/cpconDevelopingMultithreadedWindowsFormsControl.as p
You should use Control.Invoke method to marshal the manipulating to the GUI
control from another thread. Below is my modified sample code snippet:
DataTable dt;
private void Form1_Load(object sender, EventArgs e)
{
dt = new DataTable();
dt.Columns.Add("column1", typeof(int));
dt.Columns.Add("column2", typeof(string));
for (int i = 0; i < 5; i++)
{
DataRow dr = dt.NewRow();
dr["column1"] = i;
dr["column2"] = "item" + i.ToString();
dt.Rows.Add(dr);
}
this.dataGridView1.DataSource = dt;
FileSystemWatcher fsw = new FileSystemWatcher("C:\\");
fsw.EnableRaisingEvents = true;
fsw.Created += new FileSystemEventHandler(fsw_Created);
}
void fsw_Created(object sender, FileSystemEventArgs e)
{
this.dataGridView1.Invoke(new EventHandler(button1_Click));
}
private void button1_Click(object sender, EventArgs e)
{
DataRow dr=this.dt.NewRow();
dr["column1"] = 1000;
dr["column2"] = "NewItem";
dt.Rows.Add(dr);
}
This code snippet works well on my side. If I create a new file in the
"C:\" folder, a new row will be added to the DataGridView. I have also
attached the modified project in this reply for your reference.
I hope this will resolve your problem. If you still have any problem of
resolving it, please feel free to tell me, I will work with you.
Thanks!
Best regards,
Jeffrey Tan
Microsoft Online Community Support
==================================================
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
==================================================
This posting is provided "AS IS" with no warranties, and confers no rights.