Sunday, November 6, 2011

Capture The DataGridView CheckBox Column Click Event

The .Net DataGridView CheckBox Column control can be a bit tricky to use. Recently I've encountered a problem where I need to do some calculations when a user checks or unchecks the CheckBox. However, the events triggered always seems to return the previous value. E.g. When the CheckBox is checked (true), the value is captured as uncheck (false), and vice-versa.

After some digging around, I found that using both "CellContentClick" and "CellContentDoubleClick" events can do the trick.

For example, we have a grid named "myGrid" with columns "colTick" (the CheckBox) and "colAmt" (an amount field). Bind this grid to the following 2 events:
private void myGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    GetTotalSelection(e.ColumnIndex, e.RowIndex);
}

private void myGrid_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
{
    GetTotalSelection(e.ColumnIndex, e.RowIndex);
}
Then we process the checked row values in the "GetTotalSelection" method, accumulating the total selected amount into a private variable "_totalSelAmt":
private decimal _totalSelAmt = 0;
....

/// <summary>
/// Calculates total amount selected.
/// </summary>
private void GetTotalSelection(int colIndex, int rowIndex)
{
    if (colIndex < 0 || rowIndex < 0)
        return;

    if (myGrid.Columns[colIndex].Name != colTick.Name)
        return;

    myGrid.EndEdit();

    bool tick      = Convert.ToBoolean(myGrid[colIndex, rowIndex].Value);     // Gets the current row check value.
    decimal selAmt = Convert.ToDecimal(myGrid[colAmt.Name, rowIndex].Value);  // Gets the current row amount.

    if (tick)
        _totalSelAmt += selAmt;
    else
        _totalSelAmt -= selAmt;
}
Now, every time a user checks or unchecks the CheckBox, the variable "_totalSelAmt" will be updated with the latest total selected amount.


If you find this post helpful, would you buy me a coffee?


No comments:

Post a Comment