在VB.NET WinForms项目,我创造了VS2013我有这样的代码来检测的DataGridView的编程方式,有色背景:这个问题如何当一个DataGridView的单元格内容改变时保留在排序
Private Sub dgvEmployees_CellValueChanged(sender As Object, e As DataGridViewCellEventArgs) Handles dgvEmployees.CellValueChanged
' Pass the row and cell indexes to the method so we can change the color of the edited row
CompareDgvToDataSource("employees", e.RowIndex, e.ColumnIndex)
End Sub
Private Sub CompareDgvToDataSource(ByVal dataSetName As String, ByVal rowIndex As Integer, ByVal columnIndex As Integer)
' Takes a dataset and the row and column indexes, checks if the row is different from the DataSet and colors the row appropriately
EmployeesBindingSource.EndEdit()
Dim dsChanges As DataSet = EmployeesDataSet.GetChanges()
If Not dsChanges Is Nothing Then
For Each dtrow As DataRow In dsChanges.Tables("employees").Rows
If DirectCast(dtrow, EmployeesDataSet.employeesRow).employeeID.ToString = dgvEmployees.Rows(rowIndex).Cells("employeeID").Value.ToString Then
For i As Integer = 0 To dsChanges.Tables("employees").Columns.Count - 1
If dtrow.RowState.ToString = DataRowState.Added.ToString Then
' TODO: Color entire new row
ElseIf dsChanges.Tables(dataSetName).Rows(0).HasVersion(DataRowVersion.Original) Then
If Not dtrow(i, DataRowVersion.Current).Equals(dtrow(i, DataRowVersion.Original)) Then
Console.WriteLine("Employees ID: " & DirectCast(dtrow, EmployeesDataSet.employeesRow).employeeID)
dgvEmployees.Rows(rowIndex).Cells(columnIndex).Style.BackColor = Color.LightPink
Else
' TODO: Need to change the BackColor back to what it should be based on its original alternating row color
End If
End If
Next
End If
Next
End If
End Sub
是,如果用户将DGV与任何已着色的单元格进行排序,则在排序之后,没有任何单元格被着色。
在排序后,我需要做些什么才能为正确的单元格保留单元格背景颜色?
最终工作守则
Private Sub CompareDgvToDataSource()
' Force ending Edit mode so the last edited value is committed
EmployeesBindingSource.EndEdit()
Dim dsChanged As DataSet = EmployeesDataSet.GetChanges(DataRowState.Added Or DataRowState.Modified)
If Not dsChanged Is Nothing Then
Dim dtChanged As DataTable = dsChanged.Tables("employees")
For Each row As DataRow In dtChanged.Rows
For Each dgvRow As DataGridViewRow In dgvEmployees.Rows
If dgvRow.Cells("employeeID").Value IsNot Nothing Then
If dgvRow.Cells("employeeID").Value.Equals(row.Item("employeeID")) Then
' Found the row in the DGV that matches the current Changed Row
For i As Integer = 0 To dtChanged.Columns.Count - 1
If Not row(i, DataRowVersion.Current).Equals(row(i, DataRowVersion.Original)) Then
' Found a Cell in the current DGV row that is different from the DataSet
Console.WriteLine("Row index: " & dtChanged.Rows.IndexOf(row))
dgvEmployees.Rows(dgvRow.Index).Cells(i + 1).Style.BackColor = Color.LightPink
Else
' Need to change the BackColor back to what it should be based on its original alternating row color
End If
Next
End If
End If
Next
Next
End If
End Sub
这可能是一个愚蠢的问题,但你不能只处理“排序”事件,并添加自己的程序在那里着色? – Keith 2014-12-03 16:23:41