Thursday, September 06, 2007

Toggling All Cells in a DataGridViewCheckBoxColumn

Problem: Need to toggle all cells in a DataGridViewCheckBoxColumn.  We’re using a dynamically generated set of checkbox columns starting after two static columns.

Solution: 

private void dataGridView1_ColumnHeaderMouseClick(object sender,

                                              DataGridViewCellMouseEventArgs e)

{

    int colNumber = e.ColumnIndex;

    if (colNumber > ROLE_COLUMN_START_POSITION)

    {

        bool selectAll = (bool) dataGridView1.Rows[1].Cells[colNumber].FormattedValue;

        foreach (DataGridViewRow row in dataGridView1.Rows)

        {

            row.Cells[colNumber].Value = !selectAll;

        }

    }

}

Adapted from a couple Google hits.  Yes, it’s based off the value already extant in row one, but hey, it’s just ducky.

(Thanks to Kramer for getting the grid built and populated in short order today!)  (Now I wish he’d just start blogging so he could write this stuff himself.)

No comments:

Subscribe (RSS)

The Leadership Journey