在Timer控件定时刷新,同时手动编辑数值,数值会被自动清除

问题描述

通过Timer控件,定时刷新DataGridView数据,同时DataGridView也可以进行编辑。这样会出现在编辑时数据会被自动刷掉的情况。

解决方案

Control.DoubleBuffered 属性
【参考来源】https://wenku.baidu.com/view/ec9430c549fe04a1b0717fd5360cba1aa9118c53.html?wkts=1683856984562&bdQuery=C%23+DoubleBuffered

  • 缓冲图形可以减少或消除显示表面部分的渐进式重绘所造成的闪烁。缓冲图形要求更新的图形资料会先写入缓冲区。然后,图形缓冲区中的资料会快速写入到显示的界面记忆体。所显示图形记忆体的相对快速切换通常会减少可能发生的闪烁。

实现方式

  • DataGridView控件
//在winform中DataGridView控件默认状态下不支持DoubleBuffered,可以通过反射实现设置双缓冲
// 代码:
public partial  class xDataGridView : DataGridView
{
}
public static class XDataGridViewH
{
    public static void SetDoubleBuffered(this xDataGridView dgv, bool opened)
    {
        Type dgvType = dgv.GetType();
        PropertyInfo properInfo = dgvType.GetProperty("DoubleBuffered", 
            BindingFlags.Instance | BindingFlags.NonPublic);
        properInfo.SetValue(dgv, opened, null);
    }
}
// 应用:
public class Test
{
	xDataGridView dgv = new xDataGridView();
	dgv.SetDoubleBuffered(true); //开启双缓冲
}
  • ListView控件
// 代码:
public class DoubleBufferListView : ListView
{
    public DoubleBufferListView()
    {
        //开启双缓冲
        SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
        SetStyle(ControlStyles.EnableNotifyMessage, true);
    }
    protected override void OnNotifyMessage(Message m)
    {
        if (m.Msg != 0x14)
            base.OnNotifyMessage(m);
    }
}
// 应用:
public class Test
{
	DoubleBufferListView listView1 = new DoubleBufferListView();
}
posted @ 2025-06-21 14:45  JuneSolsticeYeah  阅读(4)  评论(0)    收藏  举报