Jimmy
Jimmy

Reputation: 2106

Capturing Checkbox click event in Windows Forms DataGridview

I have a Winforms DataGridView in my application.

I've two checkbox columns along with 5 other columns from the database. These two checkbox columns are added usng DataGridViewCheckBoxColumn.

When the user clicks on the 2nd checkbox, I need to show a message to the user if the first checkbox is not checked for that row.

How do I go about this? I tried this,but the cell value is coming as null. What am i doing wrong?

private void dgTest_CellClick(System.Object sender, DataGridViewCellEventArgs e)
{
    DataGridViewCheckBoxCell officialCbCell = row.Cells[1] as DataGridViewCheckBoxCell;
    DataGridViewCheckBoxCell includeCbCell = row.Cells[0] as DataGridViewCheckBoxCell;

    if (officialCbCell != null)
    {
        if (officialCbCell.Value != null && (bool)officialCbCell.Value == true)
        {
            if (includeCbCell != null && (bool)includeCbCell.Value == false)
            {
                MessageBox.Show("INVALID");
            }
        }
    }
}

Thanks.

Upvotes: 0

Views: 16227

Answers (2)

Nime Cloud
Nime Cloud

Reputation: 6395

CellContentClick event and cell.EditingCellFormattedValue property are also useful if you just un/clicked the cell.

Upvotes: 1

V4Vendetta
V4Vendetta

Reputation: 38210

You can try using the CellValueChanged event of the grid

void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == 0)
    {
        bool isChecked = (Boolean) dataGridView1[0, e.RowIndex].FormattedValue;

        if (isChecked)
            dataGridView1[1, e.RowIndex].Value = true;
    }
}

if checked then you can set the other column as also checked or any other validation

Upvotes: 7

Related Questions