如何在Datagridview排序后获取更改的单元格或添加的行



我有一个数据源如下的DatagridView:

bindingSource = DataTable
dataGridView.DataSource = bindingSource

当编辑单元格或添加新行时,我会应用不同的格式样式,如果我对dataGridView进行排序,点击其中一个列标题,格式样式就会丢失,所以我的问题是:

对数据网格进行排序后,如何知道哪些单元格发生了更改或添加了?,这样我就可以重新应用格式样式

VB.Net或C#正常

我最终实现了所需的功能,向Datatable添加了一个新的字段/列,而不是为该字段中的整行只保留一个值,我存储了表示每个单元格的状态/样式的字符串,如",,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

我希望这能帮助

相关内容

最新更新