选中CheckBox时更改DataGridView行的颜色。

时间:2014-01-08 05:42:48

标签: c# .net vb.net datagridview

我有一个绑定到DataSet的DataGridView。我有一个CheckBox列。当用户检查特定行时,我希望行改变颜色。我可以用我的代码更改颜色,但由于某些原因我不知道......只有当我离开单元格时,颜色才会改变。

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...

3 个答案:

答案 0 :(得分:0)

将此代码写在代码上方

dataGridView.CommitEdit(DataGridViewDataErrorContexts.Commit);

答案 1 :(得分:0)

试试这个......

 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

答案 2 :(得分:0)

事实证明我必须使用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