>我有一个绑定到数据集的DataGridView。我有一个复选框列。当我希望该行在用户检查特定行后立即更改颜色时。我能够用我的代码更改颜色,但由于某种我不知道的原因。只有当我离开单元格时,颜色才会改变。
Private Sub DataGridView1_CellValueChanged(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellValueChanged
If DataGridView1.Columns(e.ColumnIndex).Name = "ColCheck" Then
If DataGridView1.Rows(e.RowIndex).Cells("ColCheck").Value = True Then
DataGridView1.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.LightGreen
''' blah blah blah...
在你的
代码上面写这个
dataGridView.CommitEdit(DataGridViewDataErrorContexts.Commit);
试试这个...
Private Sub dataGridView1_CellValueChanged(sender As Object, e As DataGridViewCellEventArgs)
If DataGridView1.Columns(e.ColumnIndex).Name = "ColCheck" Then
If DataGridView1.Rows(e.RowIndex).Cells("ColCheck").Value = True Then
Dim isChecked As Boolean = DirectCast(dataGridView1(e.ColumnIndex, e.RowIndex).FormattedValue, [Boolean])
If isChecked Then
DataGridView1.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.LightGreen
End If
End If
End If
End Sub
事实证明,我必须使用CurrentCellDirtyStateChanged
Private Sub DataGridView1_CurrentCellDirtyStateChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DataGridView1.CurrentCellDirtyStateChanged
If DataGridView1.IsCurrentCellDirty Then
DataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit)
End If
End Sub