Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent DataGridView from flickering when scrolling horizontally?

I am using windows forms C#.

Screen Shot

As shown in the screen shot, I have a Form which has a user control, a tab control and a DataGridView (30 rows and 17 columns). I read data from SQL Server to fill the DataGrdiView.

The issue:

When I scroll horizontally the DataGridView flickers a lot. However scrolling vertically works perfect with no flickering.

I had a look here, here, here and here but none of them related to my issue.

Anyone knows any solution to prevent DataGridView from flickering when scrolling horizontally.

like image 953
Sam Avatar asked Jan 27 '17 12:01

Sam


3 Answers

use this class

public static class ExtensionMethods
{
   public static void DoubleBuffered(this DataGridView dgv, bool setting)
   {
      Type dgvType = dgv.GetType();
      PropertyInfo pi = dgvType.GetProperty("DoubleBuffered", BindingFlags.Instance | BindingFlags.NonPublic);
      pi.SetValue(dgv, setting, null);
   }
}

and enter this code.

this.dataGridView1.DoubleBuffered(true);

enjoy.

like image 190
Ramgy Borja Avatar answered Nov 17 '22 23:11

Ramgy Borja


All you need is to use a DoubleBuffered DataGridview subclass:

class DBDataGridView : DataGridView
{
    public DBDataGridView() { DoubleBuffered = true; }
}

It is also possible to inject double-buffering into a normal out-of-the-box control, but I prefer to have a class of my own as this is extensible in other ways as well..

I have expanded the class by a public property to allow turning DoubleBuffering on and off..:

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

    public DBDataGridView()
    {
        DoubleBuffered = true;
    }
}

..and tested it with a load of 200 columns and 2000 rows. The difference is obvious; while vertical scrolling did work without horizontal scrolling needs DoubleBuffering..

enter image description here

Note that the Form also has a DoubleBuffering property, but that will not propagate to any embedded controls!

Or you can use a function like this

like image 38
TaW Avatar answered Nov 17 '22 22:11

TaW


In your 'FormLoad' function just enter this line of code.

yourDataGridView.GetType().GetProperty("DoubleBuffered", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(yourDataGridView, true, null);

and import BindingFlags by writing below line on top.

using System.Reflection;
like image 30
Khalil Avatar answered Nov 17 '22 23:11

Khalil