如何在水平滚动时防止DataGridView闪烁?

时间:2017-01-27 12:10:41

标签: c# winforms datagridview

我正在使用Windows表单C#。

Screen Shot

如屏幕截图所示,我有一个Form,它有一个用户控件,一个tab控件和一个DataGridView(30行和17列)。我从SQL Server读取数据以填充DataGrdiView。

问题:

当我横向滚动时,DataGridView会闪烁很多。然而,垂直滚动工作完美,没有闪烁。

我看了herehereherehere,但没有一个与我的问题有关。

任何人都知道在横向滚动时阻止DataGridView闪烁的任何解决方案。

4 个答案:

答案 0 :(得分:11)

您只需使用DoubleBuffered DataGridview 子类

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

也可以将双缓冲注入到正常的开箱即用控件中,但我更喜欢拥有自己的类,因为它在其他方面也是可扩展的。

我已经通过公共属性扩展了该类,以允许打开和关闭DoubleBuffering ..:

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

    public DBDataGridView()
    {
        DoubleBuffered = true;
    }
}

..并使用 200列 2000行加载测试。差异很明显;虽然垂直滚动确实有效,但没有水平滚动需要DoubleBuffering ..

enter image description here

请注意,表单还具有DoubleBuffering属性,但会传播到任何嵌入式控件!

或者您可以使用function like this

答案 1 :(得分:8)

使用此课程

def main():
    result = int(input("Enter a whole, positive, number to be converted to hexadecimal: "))
    hexadecimal = ""
    while result != 0:
        remainder = changeDigit(result % 16)
        hexadecimal = str(remainder) + hexadecimal
        result = int(result / 16)
    print(hexadecimal)

def changeDigit(digit):
    decimal =     [10 , 11 , 12 , 13 , 14 , 15 ]
    hexadecimal = ["A", "B", "C", "D", "E", "F"]
    for counter in range(7):
        if digit == decimal[counter - 1]:
            digit = hexadecimal[counter - 1]
    return digit

main()

并输入此代码。

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);
   }
}

享受。

答案 2 :(得分:2)

在“ FormLoad”功能中,只需输入以下代码即可。

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

并通过在顶部下面的行中编写来导入BindingFlags。

using System.Reflection;

答案 3 :(得分:0)

万一有人想在Visual Basic中看到它。

Public Class DBDataGridView
    Inherits DataGridView

    Public Sub New()
        MyBase.New()
        DoubleBuffered = True
    End Sub

End Class

效果很好。