Fixing the DataGridView "Red X" Error
Written by Herb Fickes   
Wednesday, 10 March 2010 14:02

The DataGridView is a common .Net control used to display and permit editing of tabular data.  It can be filled in via code or by attaching a data source to it.

DataGridViews, like most controls, are not thread-safe.  That is, you need to perform operations on them using the same thread as they were created on.  However, sometimes OpenSpan developers will accidently modify the DataGridView from another thread because the operation is coming from an event in another application.

A safe way to correct this problem and to ensure it doesn't accidently happen is to postpone updating the control during a OnPaint() event if it happens from another thread.  This is done by handling an exception and then flagging the control to be redrawn when the MessagePump is run. 

You can do this by creating a .Net class that inherits from DataGridView and overrides the OnPaint() event.  You will need access to a C# compiler to build this.  Once built, you add it to the OpenSpan Studio Toolbox and replace your DataGridView controls with it.

using System;
using System.Windows.Forms;
 
namespace DataGridViewPlus
{
    public class DataGridViewPlus : DataGridView
    {
        ///
        /// This prevents the "red X" error which happens when you cause updates to a datagrid
        /// from multiple threads.  It catches the OnPaint() exception and invalidates
        /// the grid so it gets redrawn the next time the application hits its message loop.
        ///
        /// The following solution to this problem was found
        /// at
http://social.msdn.microsoft.com/forums/en-US/winforms/thread/fdd94896-80e9-4e91-9ed5-0348bf2633a9
        ///
        protected override void OnPaint( PaintEventArgs e ) 
       {
            try
            {
                base.OnPaint( e );
            }
            catch
            {
                Invalidate();
            }
        }
    }
}