[Solved] Flickering and Corruption Problem with DataGridView

While working with DataGridView, which is one of the controls of Winforms, I saw that there was a corruption during scrolling. especially when swiping the horizontal scroll to the left, the cells were getting mixed up and not creating a nice view. Also flickering occurred due to too many columns in DataGridView.


Solution of the corruption

I solved the first problem, the corruption, by refreshing the DataGridView. To solve this problem, it was enough to write a few events on the scrollbar:

        ...

        PropertyInfo property = dataGridView.GetType().GetProperty(
            "HorizontalScrollBar", BindingFlags.NonPublic | BindingFlags.Instance
        );
        scrollBar = (ScrollBar)property.GetValue(dataGridView, null);
        scrollBar.MouseCaptureChanged += (o, e) => {this.dataGridView.Refresh();};
        scrollBar.MouseLeave += (o, e) => {this.dataGridView.Refresh();};
        scrollBar.Scroll += (o, e) => {this.dataGridView.Refresh();};
        scrollBar.MouseEnter += (o, e) => {this.dataGridView.Refresh();};
        scrollBar.MouseWheel += (o, e) => {this.dataGridView.Refresh();};
        
        ...
As a result, distortions are prevented. But I wouldn't say it works perfectly. It just seems to be working fine. 

Solution of the flickering

We must set the DataGridView's property called DoubleBuffered as true to solve the other problem. You can find this code on the Internet easily.

No comments:

Post a Comment