在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