Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flickering during updates to Controls in WinForms (e.g. DataGridView)

Tags:

c#

.net

winforms

In my application I have a DataGridView control that displays data for the selected object. When I select a different object (in a combobox above), I need to update the grid. Unfortunately different objects have completely different data, even different columns, so I need to clear all the existing data and columns, create new columns and add all the rows. When this is done, the whole control flickers horribly and it takes ages. Is there a generic way to get the control in an update state so it doesn't repaint itself, and then repaint it after I finish all the updates?

It is certainly possible with TreeViews:

myTreeView.BeginUpdate();
try
{
    //do the updates
}
finally
{
    myTreeView.EndUpdate();
}

Is there a generic way to do this with other controls, DataGridView in particular?

UPDATE: Sorry, I am not sure I was clear enough. I see the "flickering", because after single edit the control gets repainted on the screen, so you can see the scroll bar shrinking, etc.

like image 575
Grzenio Avatar asked Sep 15 '08 15:09

Grzenio


People also ask

How to stop flickering c# Winforms?

use control. DoubleBuffered property. set it to true. DoubleBuffered allows Control redraws its surface using secondary buffer to avoid flickering.

What is difference between DataGridView and DataGrid control in Winforms?

The DataGrid control is limited to displaying data from an external data source. The DataGridView control, however, can display unbound data stored in the control, data from a bound data source, or bound and unbound data together.

What is double buffering in c#?

Double buffering uses a memory buffer to address the flicker problems associated with multiple paint operations. When double buffering is enabled, all paint operations are first rendered to a memory buffer instead of the drawing surface on the screen.

How to turn on double buffering?

You can enable default double buffering in your forms and authored controls in two ways. You can either set the DoubleBuffered property to true , or you can call the SetStyle method to set the OptimizedDoubleBuffer flag to true .


1 Answers

People seem to forget a simple fix for this:

Object.Visible = false;

//do update work

Object.Visible = true;

I know it seems weird, but that works. When the object is not visible, it won't redraw itself. You still, however, need to do the begin and end update.

like image 152
Jon Avatar answered Oct 08 '22 12:10

Jon