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

时间:2013-06-21 14:55:02

标签: c# .net vb.net datagridview

我有一个带有数据源的DatagridView,如下所示:

bindingSource = DataTable
dataGridView.DataSource = bindingSource

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

在对datagridview进行排序之后,我如何知道哪些单元格已更改或已添加?,因此我可以重新应用格式化样式

VB .Net或C#没问题

1 个答案:

答案 0 :(得分:0)

我终于实现了向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

我希望这有助于某人

相关问题