Hi George,
Thanks for your feedback information!
Yes, I think your background information is critical regarding resolving
your problem.
FileSystemWatch er 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:
"Multithrea ded Windows Forms Control Sample"
http://msdn.microsoft.com/library/de...us/cpguide/htm
l/cpconDeveloping MultithreadedWi ndowsFormsContr ol.asp
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(obje ct 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.dataGridVi ew1.DataSource = dt;
FileSystemWatch er fsw = new FileSystemWatch er("C:\\");
fsw.EnableRaisi ngEvents = true;
fsw.Created += new FileSystemEvent Handler(fsw_Cre ated);
}
void fsw_Created(obj ect sender, FileSystemEvent Args e)
{
this.dataGridVi ew1.Invoke(new EventHandler(bu tton1_Click));
}
private void button1_Click(o bject sender, EventArgs e)
{
DataRow dr=this.dt.NewR ow();
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.