我正在使用此代码:
// Cell value change event.
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if ((bool)dataGridView1.CurrentCell.Value == true) MessageBox.Show("true");
if ((bool)dataGridView1.CurrentCell.Value == false) MessageBox.Show("false");
MessageBox.Show(dataGridView1.CurrentCell.Value.ToString());
}
它适用于所有列,除了带有复选框的一列 (
DataGridViewCheckBoxColumn
)
我需要知道复选框列中的值(真或假)。
为此我需要做什么?
使用
DataGridViewCheckBoxColumn
有时可能会有点棘手,因为有一些规则专门适用于此列类型的 Cells
。此代码应该可以解决您遇到的问题。
单击单元格时,
CurrentCellDirtyStateChanged
事件会立即提交更改。您在调用 CellValueChanged
方法时手动引发 CommitEdit
事件。
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.CurrentCell == null) return;
if ((bool)dataGridView1.CurrentCell.Value == true) MessageBox.Show("true");
if ((bool)dataGridView1.CurrentCell.Value == false) MessageBox.Show("false");
MessageBox.Show(dataGridView1.CurrentCell.Value.ToString());
}
private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (dataGridView1.IsCurrentCellDirty)
{
dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}
访问此处,了解有关使用
DataGridViewCheckBoxCell
的更多信息。
MSDN 说here CellValueChanged 在单元格失去焦点之前不会触发。
一些解决方案:
http://codingeverything.blogspot.com/2013/01/firing-datagridview-cellvaluechanged.html
我想出了一个稍微不同的解决方案。
我使用 CurrentCellDirtyStateChanged 事件来检查该列是否为复选框列,如果是,我手动触发 CellValueChanged 事件,如下所示:
if (DGV_Charge.CurrentCell.ColumnIndex == 0) DGV_Charge_CellValueChanged(null, new DataGridViewCellEventArgs(DGV_Charge.CurrentCell.ColumnIndex, DGV_Charge.CurrentCell.RowIndex));
最好的方法是通过创建自己的网格来扩展网格,并准备好这些各种“技巧”。相信我,这个网格中有很多东西需要调整。
建议使用的代码
Public Class MyGrid
Inherits Windows.Forms.DataGridView
Private Sub MyGrid_CurrentCellDirtyStateChanged(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles Me.CurrentCellDirtyStateChanged
If Me.IsCurrentCellDirty AndAlso Not Me.CurrentCell Is Nothing Then
If TypeOf Me.Columns(Me.CurrentCell.ColumnIndex) Is DataGridViewCheckBoxColumn Then
Me.CommitEdit(DataGridViewDataErrorContexts.Commit) 'imediate commit, not only on focus changed
End If
End If
End Sub
Private Sub MyGrid_CellValueChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs)
Handles Me.CellValueChanged
If e.RowIndex >= 0 AndAlso e.ColumnIndex >= 0 Then
Dim Checked As Boolean = False
If TypeOf Me.Columns(e.ColumnIndex) Is DataGridViewCheckBoxColumn Then
'avoid erros
Checked = Me.CellChecked(e.RowIndex, e.ColumnIndex)
End If
RaiseEvent Change(e.RowIndex, e.ColumnIndex, Checked)
End If
End Sub
End Class
我喜欢 @Andrew Phillips 解决方案使用 CurrentCellDirtyStateChanged 事件,因为它看起来很简单,只有一行代码。就我而言,我有几个需要评估的 CheckBox 列,因此我做了一些修改,使其保持一行,并在任何 CheckBox 列的单元格被修改时触发:
if (DGV_Charge.Columns[DGV_Charge.CurrentCell.ColumnIndex] is DataGridViewCheckBoxColumn) DGV_Charge_CellValueChanged(null, new DataGridViewCellEventArgs(DGV_Charge.CurrentCell.ColumnIndex, DGV_Charge.CurrentCell.RowIndex));