update datagridview very frequently

The number of cells you want to update and also the update rate you want are high enough to cause flicker and lagging.

To avoid it you can turn on DoubleBuffering for the DataGridView.

This property is not exposed by default. So have a have a choice of either

  • creating a subclass or
  • accessing it via reflection

Here is a post that demonstrates the former. It was written for a case of scrolling flicker but will help avoid update lags as well. The class can maybe look like this:

public class DBDataGridView : DataGridView
{
    public new bool DoubleBuffered
    {
        get { return base.DoubleBuffered; }
        set { base.DoubleBuffered = value; }
    }

    public DBDataGridView()
    {
        DoubleBuffered = true;
    }
}

You can add this class to the project or simply to the form class (before the very last curly.) Compile and it will show up in the ToolBox.

The other option uses reflection; here is a general-purpose function that should work for for any type of control:

using System.Reflection;

static void SetDoubleBuffer(Control ctl, bool DoubleBuffered)
{
    typeof(Control).InvokeMember("DoubleBuffered", 
        BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetProperty, 
        null, ctl, new object[] { DoubleBuffered });
}

Both ways let you turn DoubleBuffering on and off at will; the former via the now exposed property, the latter by the bool param of the method.

Leave a Comment