This content has been archived and is no longer being maintained.

Table of Contents

Article

Example: Correcting the DataGridView Red X error

The DataGridView is a .NET control that is used to display and permit the editing of tabular data. The grid can be filled in by using code or by attaching a data source.

DataGridView controls, like most controls, are not thread-safe. That is, you need to perform operations on them within the same thread in which they were created. Sometimes, however, Pega® Robotic Automation Studio developers accidentally modify the DataGridView control from another thread. This typically happens when an operation is coming from an event in another application.

To correct this problem and make sure that it does not accidentally happen again, postpone the updating of the DataGridView control during an OnPaint event if it is triggered from another thread. You do this by handling an exception and then flagging the control to be redrawn when the Message Pump runs.

Create a .NET class that inherits from the DataGridView control and overrides the OnPaint event. You must have a C# compiler to build this. Once built, add it to the Robotic Automation Studio toolbox and replace your DataGridView controls with it.

The following is an example:

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
        /// <a href="http://social.msdn.microsoft.com/forums/en-US/winforms/thread/fdd94896-80e9-4e91-9ed5-0348bf2633a9" style="color: #008000;">http://social.msdn.microsoft.com/forums/en-US/winforms/thread/fdd94896-80e9-4e91-9ed5-0348bf2633a9</a>
        ///
        protected override void OnPaint( PaintEventArgs e )
        {
            try
            {
                base.OnPaint( e );
            }
            catch
            {
                Invalidate();
            }
        }
    }
}

Published December 6, 2016 — Updated March 8, 2018


50% found this useful

Have a question? Get answers now.

Visit the Pega Support Community to ask questions, engage in discussions, and help others.