【问题标题】:How to get the changed cells or added rows after Datagridview SortDatagridview排序后如何获取更改的单元格或添加的行
【发布时间】:2013-06-28 01:43:14
【问题描述】:

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

bindingSource = DataTable
dataGridView.DataSource = bindingSource

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

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

VB .Net 或 C# 都可以

【问题讨论】:

  • 你可以使用另一个列(折叠),带有一个布尔值,然后对新值为真的行应用样式,当为假时什么也不做。
  • 对于似乎工作的整行但对于特定单元格?情况是我需要知道特定的单元格,所以我可以将样式仅应用于那些单元格而不是整行

标签: c# .net vb.net datagridview


【解决方案1】:

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

我希望这对某人有所帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-07
    • 1970-01-01
    • 2014-07-13
    • 1970-01-01
    • 2021-06-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多