簡體   English   中英

在單元格值更改時重新排序 Datagridview

[英]Reordering a Datagridview on Cell Value Change

我目前在單元格值更改后嘗試重新排序 datagridview 時遇到問題。 在特定列中的值發生更改后,我想根據這個新值對列進行重新排序。 但是,它的排序並不完全正確。

例如,假設我從下圖中的 datagridveiw 開始。 在此處輸入圖像描述

然后我對第一行的 Line 列進行更改並將其重新編號為 8。此時我想將第 1 行移動到當前第 8 行所在的位置,然后每隔一行重新編號。

我已經實現了以下代碼來做到這一點。

    Dim OuterSourceRowIndex As Integer
    Dim InnerSourceRowIndex As Integer

    If e.ColumnIndex = 0 Then
        For Each rowOuter As DataGridViewRow In dgvReceive.Rows
            For Each rowInner As DataGridViewRow In dgvReceive.Rows
                OuterSourceRowIndex = rowOuter.Index
                InnerSourceRowIndex = rowInner.Index
                If rowOuter.Cells(0).Value >= rowInner.Cells(0).Value Then
                    dgvReceive.Rows.RemoveAt(OuterSourceRowIndex)
                    dgvReceive.Rows.Insert(InnerSourceRowIndex, rowOuter)
                End If
            Next
        Next

        For Each row As DataGridViewRow In dgvReceive.Rows
            row.Cells(0).Value = row.Index + 1
        Next
    End If

當我嘗試實際進行更改時,雖然我最終得到以下內容,其中第 1 行實際上移動到 position 7。所有這些都發生在 CellValueChanged 事件上在此處輸入圖像描述

如果之前已經回答過這個問題,我深表歉意。 我找不到像這樣的東西。 感謝您提供的任何幫助。

您可能使用這些雙循環使這變得更加復雜。 此外,您應該避免 For-Each 循環,因為您在循環時正在修改集合。

錯誤檢查不多,但這是一個簡化版本。 它刪除您更改的行,將其插入適當的位置,然后重新編號所有內容。

If e.ColumnIndex = 0 Then
  RemoveHandler dgvReceive.CellValueChanged, AddressOf dgvReceive_CellValueChanged
  Dim thisRow As DataGridViewRow = dgvReceive.Rows(e.RowIndex)
  dgvReceive.Rows.Remove(thisRow)
  dgvReceive.Rows.Insert(CInt(thisRow.Cells(0).Value) - 1, thisRow)
  For Each row As DataGridViewRow In dgvReceive.Rows
    row.Cells(0).Value = row.Index + 1
  Next
  AddHandler dgvReceive.CellValueChanged, AddressOf dgvReceive_CellValueChanged
End If

我添加了 RemoveHandler 和 AddHandler 行,以防止在重新編號行項目時更改所有這些單元格值時觸發過多的煙花。

暫無
暫無

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

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