簡體   English   中英

編輯時防止數據綁定DataGridView排序

[英]Prevent databound DataGridView from sorting while editing

我在Win Forms應用程序中有一個數據綁定DataGridView,用戶可能已按列排序。 問題是這樣的:在用戶在排序列中編輯單元格后離開行之后,該行立即被重新排序。

這對於用戶來說非常迷惑,並且使得編輯行組成不可能。

我正在尋找的解決方案將在初始排序后有效地禁用自動重新排序,然后僅在用戶請求時再次排序。

為了別人的利益,這是我提出的解決方案,但我很想聽到更好的解決方案。

我在DataTable中添加了一個名為SORT_ORDER的附加非持久列,該列僅用於排序。

當用戶單擊要排序的列時,我將值和值類型從選定列復制到SORT_ORDER列,然后對SORT_ORDER進行排序。 由於SORT_ORDER不可見且無法編輯,因此即使用戶編輯所選列,排序順序也不會更改。 事件處理程序如下所示:

    private void MyDataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) {
        dirtyCellListenerEnabled = false;

        SORT_ORDER.ValueType = MyDataGridView.Columns[e.ColumnIndex].ValueType;

        foreach(DataGridViewRow r in MyDataGridView.Rows) {
            r.Cells[SORT_ORDER.Index].Value = r.Cells[e.ColumnIndex].Value;
        }

        switch(MyDataGridView.SortOrder) {
            case System.Windows.Forms.SortOrder.None:
                MyDataGridView.Sort(SORT_ORDER, ListSortDirection.Ascending);
                break;
            case System.Windows.Forms.SortOrder.Ascending:
                MyDataGridView.Sort(SORT_ORDER, ListSortDirection.Descending);
                break;
            case System.Windows.Forms.SortOrder.Descending:
                MyDataGridView.Sort(SORT_ORDER, ListSortDirection.Ascending);
                break;
        }
        dirtyCellListenerEnabled = true;
    }

請注意,我必須禁用並重新啟用我的單元格偵聽器,以便我的代碼不會將排序列更新視為真正的更改。

在到達此解決方案之前,我還嘗試將排序列添加到DataGridView,但它不起作用,因為DataGridView無法對其數據源中不存在的列進行排序。

我確信我還可以做一些其他的調整,例如在填充SORT_ORDER並在所選列上顯示排序字形時暫停更新。

這是一個真正的痛苦,因為我現在發現。 網格有時候看起來很殘酷

對於每個選定的單元格,我存儲主鍵和網格列的名稱(我做了一個小類來保存它們)。

然后我將它們全部扔進一個列表並迭代它們以進行更新。 每次我更新一個單元格值時,我會搜索實際單元格的位置,並將我的本地引用變量替換為該單元格,這樣我就可以繼續使用代碼了。

       Cell.Value = ValueToWrite
       Cell = FindCell(Cell.OwningRow.DataGridView, DataRow, ColName)

Function FindCell(Grid As DataGridView, DataRow As DataRow, ColName As String) As DataGridViewCell
    'Find the same cell, wherever you may be now, damn you sort.
    Dim GridRow = (From x As DataGridViewRow In Grid.Rows Where x.DataBoundItem.row Is DataRow).FirstOrDefault
    Dim Cell = GridRow.Cells(ColName)
    Return Cell
End Function

我遇到了這個問題並且得不到合適的答案,所以我嘗試了這個並且它有效,

    private void SortBoundDG()
    {
        DataTable TempTable;
        TempTable = (DataTable)DG.DataSource;
        TempTable.DefaultView.Sort =  ColumnName + " " + "DESC";
        DG.DataSource = TempTable.DefaultView.ToTable();
    }

只需將defaultview轉換回表格並將其設置為datagridview的源

聽起來你的GridView是重新綁定的數據。 這意味着您的排序順序將丟失。 啟用gridview的Viewstate並確保在回發時不綁定網格。

暫無
暫無

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

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