簡體   English   中英

使用BindingSource對DataGridView進行自定義排序

[英]Custom Sort on DataGridView with BindingSource

我試圖提高在DataGridView中加載相對大量數據的性能,我發現將DGV的數據源設置為完全渲染之間的時間確實很長。 我將其隔離到DataBindingComplete事件中的列格式的動態設置中,該事件(逐步查找后)不是在每個列的基礎上應用格式,而是在每個單元格的基礎上應用該格式(!!)。 當單元數量巨大時,這顯然阻塞了渲染。

我開始着手修改內存中的數據,通過value.ToString("N")將DataTable的值從double更改為格式化的字符串。 這極大地加快了渲染速度,但是我剩下的是幾列字符串,而不是破壞了網格自然排序能力的double。 我已經搜索了很多內容,如果可以在DataGridView級別,BindingSource級別或DataTable級別上進行自定義排序無濟於事。

如果有人能指出我正確的方向,尤其是這種方法完全不是一個好主意,並且有更好的方法來完成數字格式之類的簡單任務,則不勝感激。

我認為您正在尋找這篇文章 您可以通過實現IComparer<T>接口並使用自定義的Compare方法,使用LINQ自定義對BindingSource的排序(我想您是否仍在使用LINQ?)。

對於列格式,如果需要對其進行格式化,則可以像這樣進行操作,示例為dateTime值:

dataGridView1.Columns["Column"].DefaultCellStyle.Format = "MM-dd-yyyy";

對於自定義排序,如果您要從sql服務器獲取數據,則可以讓它對查詢中返回的行進行排序,並在dataGridView中的該順序中顯示它們,這是我用於此目的的代碼:

string command = "SELECT * FROM [table] ORDER BY [column]";
//database connection string
string constring =[database connection string];
//open DB connection - execute query - create dataadapter - fill datatable - bind datasource to datatable
using (SqlConnection con = new SqlConnection(constring))
    {
    using (SqlCommand cmd = new SqlCommand(command, con))
        {
        cmd.CommandType = CommandType.Text;
        using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
            {
            using (DataTable dt = new DataTable())
                {
                try
                  {
                  //fill the dataGridView
                  sda.Fill(dt);
                  dataGridView1.DataSource = dt;
                  Console.WriteLine("Refreshing Complete");
                  //disable manual sorting on all columns
                  for (int i = 0; i < dataGridView1.Columns.Count; i++)
                  {
                    dataGridView1.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
                  }
                  //Autosize all cells
                  dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
                  dataGridView1.AutoResizeColumns();
                  }
                  catch (Exception e)
                  {
                  MessageBox.Show(e.Message);
                  }
              }
          }
       }
  }

這將查詢輸出按照返回的行的順序綁定到dataGridView,將行的手動順序設置為false並自動調整所有列的大小。 如果您想重新填充dataGridView,可以使用以下方法:

dataGridView1.DataSource = null;
dataGridView1.Refresh();

然后再次運行填充。 如果需要,您還可以在綁定查詢輸出期間更改列的顯示順序和列標題名稱。 我希望這會有所幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM