Be nice, would ya?

Was doing a SQL-based "blanket" delete of a client and all its related tables. That required me to loop through all the tables involving the ClientId and deleting them. Sure I can use CASCADING, but for more control (am I a control freak?), I wanted to manually walk through them.

I used the DataGridView to display all the data and used the UserDeletingRow event to handle the Delete key. Well, at the end of the event, the application bombs from the exe (not the debugger) for "no reason" spitting out the below:

*** Exception Text ***
System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
at System.Collections.ArrayList.getItem(Int32 index)
at System.Windows.Forms.DataGridViewRowCollection.SharedRow(Int32 rowIndex)
at System.Windows.Forms.DataGridViewRowCollection.get
Item(Int32 index)
at System.Windows.Forms.DataGridView.ProcessDeleteKey(Keys keyData)
at System.Windows.Forms.DataGridView.ProcessDataGridViewKey(KeyEventArgs e)
at System.Windows.Forms.DataGridView.OnKeyDown(KeyEventArgs e)
at System.Windows.Forms.Control.ProcessKeyEventArgs(Message& m)
at System.Windows.Forms.DataGridView.ProcessKeyEventArgs(Message& m)
at System.Windows.Forms.Control.ProcessKeyMessage(Message& m)
at System.Windows.Forms.Control.WmKeyChar(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.DataGridView.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

Well, everything has a reason, and I'm sure this does too, but I want to handle the foresaken error and make nice to the users. The error doesn't affect the application at all if I press 'Continue' at the Debug dialog so...

Came across several forums saying there might be bugs in the DataGridView since MS developers might had let some things "slip". Cannot say for sure.

Then was looking for some code to handle these kind of errors if it something that cannot be handled within the class. The last entry in the error above "...Callback(..." gave me a clue that it's an asynchronous event or a threading issue.

So created an event handler in the entry point of the application:

static void Main(string[] args)

Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(ApplicationThreadException);

static void Application
ThreadException(object sender, System.Threading.ThreadExceptionEventArgs t)
Exception e = (Exception)t.Exception;
"AactsThreadExceptionHandler", e.Message, System.Diagnostics.EventLogEntryType.Error);

Hope that's instructional enough for anyone to stumble across here!