Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checkboxes in DataGridView not firing CellValueChanged event

I'm using this code:

// 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());
}

It works fine for all columns, except for one column with a checkbox (DataGridViewCheckBoxColumn)

I need to know the value in the checkbox column (true or false).

What do I need to do for this?

like image 878
user2516034 Avatar asked Jun 24 '13 12:06

user2516034


3 Answers

MSDN says here that CellValueChanged won't fire until the cell has lost focus.

Some solutions:

DataGridView.CellContentClick

http://codingeverything.blogspot.com/2013/01/firing-datagridview-cellvaluechanged.html

like image 63
Arie Avatar answered Nov 10 '22 01:11

Arie


Working with DataGridViewCheckBoxColumn can sometimes be a bit tricky since there are some rules that specifically apply only to the Cells of this column type. This code should handle the issue that you are experiencing.

The CurrentCellDirtyStateChanged event commits the changes immediately when the cell is clicked. You manually raise the CellValueChanged event when calling the CommitEdit method.

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);
    }
}

Visit here for additional information on working with the DataGridViewCheckBoxCell.

like image 36
Derek W Avatar answered Nov 10 '22 02:11

Derek W


I came up with a slightly different solution.

I use the CurrentCellDirtyStateChanged event to check if the column is the checkbox column, and if it is I manually fire the CellValueChanged event like so:

if (DGV_Charge.CurrentCell.ColumnIndex == 0) DGV_Charge_CellValueChanged(null, new DataGridViewCellEventArgs(DGV_Charge.CurrentCell.ColumnIndex, DGV_Charge.CurrentCell.RowIndex));
like image 23
Andrew Phillips Avatar answered Nov 10 '22 02:11

Andrew Phillips