C# 解决datagridview控件显示大量数据拖拉卡顿问题

问题描述:

由于在使用SQL查询大量的数据并一次显示到dataGridView控件,出现拖拉的时候卡顿。

解决方法:
1.首先分页。
2.其次把显示控件设置双buffer。

解决过程如下:

1.设置dataGridView双buffer代码如下,需要引用反射命名空间

 Type dgvType = this.dataGridView1.GetType();
      PropertyInfo pi = dgvType.GetProperty("DoubleBuffered", BindingFlags.Instance | BindingFlags.NonPublic);
      pi.SetValue(this.dataGridView1, true, null);

2.自己定义分页操作控件,上一页,下一页,首页,尾页,在加载form的时候添加事件。并为他们写一个操作事件

 private void Form1_Load(object sender, EventArgs e)
    {

      this.btn_EndPage.Click += Ctrl_Click;
      this.btn_FirstPage.Click += Ctrl_Click;
      this.btn_LastPage.Click += Ctrl_Click;
      this.btn_NextPage.Click += Ctrl_Click;


      //this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.AllPaintingInWmPaint, true);
      //this.UpdateStyles();
      
  
    }

    private void Ctrl_Click(object sender, EventArgs e)
    {
      Button btn = (Button)sender;
      if (btn.Text == this.btn_EndPage.Text)
      {
        if (currentPage == pageCount)
        { return; }
        currentPage = pageCount;
        LoadPage();
      }
      else if (btn.Text == this.btn_FirstPage.Text)
      {
        if (currentPage == 1)
        { return; }
        currentPage = 1;
        LoadPage();
      }
      else if (btn.Text == this.btn_LastPage.Text)
      {
        if (currentPage == 1)
        { return; }
        currentPage--;
        LoadPage();
      }
      else if (btn.Text == this.btn_NextPage.Text)
      {
        if (currentPage == pageCount)
        { return; }
        currentPage++;
        LoadPage();
      }
      else
      {
        MessageBox.Show("error");
      }


    }

3.下面代码是分页方法,加载page

 #region datagridview sort

    /// <summary>
    /// 每页记录数
    /// </summary>
    private int pageSize = 50;

    /// <summary>
    /// 总记录数
    /// </summary>
    private int recordCount = 0;

    /// <summary>
    /// 总页数
    /// </summary>
    private int pageCount = 0;

    /// <summary>
    /// 当前页
    /// </summary>
    private int currentPage = 0;


    /// <summary>
    /// 分页的方法
    /// </summary>
    /// <param name="str"></param>
    private void PageSorter()
    {
      foreach (DataColumn col in dt.Columns)
      {
        DataGridViewTextBoxColumn dgvc = new DataGridViewTextBoxColumn();
        dgvc.Name = "";
        dgvc.DataPropertyName = "";
        dgvc.HeaderText = col.ToString();
        dataGridView1.Columns.Add(dgvc);
      }
      recordCount = dt.Rows.Count;   //记录总行数
      pageCount = (recordCount / pageSize);
      if ((recordCount % pageSize) > 0)
      {
        pageCount++;
      }
      //默认第一页
      currentPage = 1;
      LoadPage();//调用加载数据的方法
    }


    /// <summary>
    /// LoadPage方法
    /// </summary>
    private void LoadPage()
    {
      if (currentPage < 1) currentPage = 1;
      if (currentPage > pageCount) currentPage = pageCount;

      int beginRecord;  //开始指针
      int endRecord;   //结束指针
      DataTable dtTemp;
      dtTemp = dt.Clone();

      beginRecord = pageSize * (currentPage - 1);
      if (currentPage == 1) beginRecord = 0;
      endRecord = pageSize * currentPage;

      if (currentPage == pageCount) endRecord = recordCount;
      for (int i = beginRecord; i < endRecord; i++)
      {
        dtTemp.ImportRow(dt.Rows[i]);
      }

      dataGridView1.Rows.Clear();
      this.lb_CurrentRow.Text = "当前页: " + currentPage.ToString() + " / " + pageCount.ToString();//当前页
      this.lb_TotalRows.Text = "总行数: " + recordCount.ToString() + " 行";//总记录数
                                      


      把临时table的数据插入到datagridview控件里面。
      for (int i = 0; i < dtTemp.Rows.Count; i++)
      {
        dataGridView1.Rows.Add();
        for (int j = 0; j < dtTemp.Columns.Count; j++)
          dataGridView1.Rows[i].Cells[j].Value = dtTemp.Rows[i][j].ToString();
      }
    }

    #endregion

Tips:

文中的“dt”是datatable类型的数据,给位看官可以自己创建,也可以从数据库直接获取测试数据。

Extension1:

1.设置dataGridView自增序列号

 //填充序列号
    private void dataGridView1_RowPostPaint_1(object sender, DataGridViewRowPostPaintEventArgs e)
    {
      Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
        e.RowBounds.Location.Y,
        dataGridView1.RowHeadersWidth - 4,
        e.RowBounds.Height);
      TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),
        dataGridView1.RowHeadersDefaultCellStyle.Font,
        rectangle,
        dataGridView1.RowHeadersDefaultCellStyle.ForeColor,
        TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
    }

Extension2:

1.设置dataGridView自增序列号

    //用委托更新data,防止卡顿。
    private delegate void UpdateDataGridView(DataTable dt);
    private void UpdateGV(DataTable dt)
    {
      if (dataGridView1.InvokeRequired)
      {
       //这里没有看懂,有大神可以解释下嘛
        this.BeginInvoke(new UpdateDataGridView(UpdateGV), new object[] { dt });
      }
      else
      {
        dataGridView1.DataSource = dt;
        dataGridView1.Refresh();
      }
    }
    }

到此这篇关于C# 解决datagridview控件显示大量数据拖拉卡顿问题的文章就介绍到这了,更多相关C#  datagridview拖拉卡顿内容请搜索云海天教程以前的文章或继续浏览下面的相关文章希望大家以后多多支持云海天教程!