簡體   English   中英

Datagridview Sort之后如何獲取更改的單元格或添加的行

[英]How to get the changed cells or added rows after Datagridview Sort

我有一個帶有數據源的DatagridView,如下所示:

bindingSource = DataTable
dataGridView.DataSource = bindingSource

當編輯單元格或添加新行時,我應用了另一種格式設置樣式;如果我對dataGridView進行排序,則單擊了列標題之一,則格式設置樣式丟失了,所以我的問題是:

在對datagridview排序之后,我如何知道哪些單元格已更改或添加了,所以我可以重新應用格式設置樣式

VB .Net或C#可以

最后,我實現了所需的功能,向數據表中添加了一個新的字段/列,並且對該字段中的整個行僅保留一個值,我存儲了表示每個單元格的狀態/樣式的字符串,例如“ ,, E ,, E”因此此示例字符串將指示索引2和5的單元格應具有已編輯的樣式。

我在CellValueChanged事件中創建/更改該字符串,示例:

 Private Sub DataGridView_CellValueChanged(sender As System.Object, e As DataGridViewCellEventArgs) Handles DataGridView.CellValueChanged
        If e.RowIndex = -1 Or IsNothing(DataGridView.CurrentCell) Then
            Return
        End If

        Dim cellPosition As Short = DataGridView.CurrentCell.ColumnIndex
        Dim Styles(25) As String

        Dim stylesCell = DataGridView.Rows(e.RowIndex).Cells("CellStyleDescriptor").Value

        If Not IsDBNull(stylesCell) And _
            Not IsNothing(stylesCell) Then
            Styles= Split(stylesCell, ",")
        End If

        If IsDBNull(DataGridView.Rows(e.RowIndex).Cells("Id").Value) Then
            For i As Integer = 0 To 25 'New row is being added
                Styles(i) = "N"
            Next
        Else
            Styles(cellPosition) = "E" 'Edited/Modified Cell
        End If

        DataGridView.Rows(e.RowIndex).Cells("CellStyleDescriptor").Value = String.Join(",", String)
    End Sub

並讀取/應用CellFormatting事件中的樣式,示例:

 Private Sub DataGridView_CellFormatting(sender As System.Object, e As DataGridViewCellFormattingEventArgs) Handles DataGridView.CellFormatting
        If e.RowIndex = -1 Or e.ColumnIndex = -1 Then
            Return
        End If

        Dim styles(25) As String
        styles = Split(DataGridView.Rows(e.RowIndex).Cells("CellStyleDescriptor").Value, ",")

        Select Case styles(e.ColumnIndex)
            Case "E" 'Edited cell
                e.CellStyle.BackColor = modifiedStyle.BackColor
                e.CellStyle.ForeColor = modifiedStyle.ForeColor
            Case "N" 'New cell
                e.CellStyle.BackColor = newStyle.BackColor
                e.CellStyle.ForeColor = newStyle.ForeColor
        End Select
    End Sub

我希望這可以幫助別人

暫無
暫無

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

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