You could keep a running total of the number of checkboxes that are checked on your control.
A useful property for storing that information is the
Tag
which will hold any object. As integers are objects in .NET then it will do nicely.
Here's one way of doing it
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 0 && ((DataGridView)sender).IsCurrentRowDirty)
{
int count = (this.dataGridView1.Tag != null) ? (int)this.dataGridView1.Tag : 0;
DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)((DataGridView)sender).Rows[e.RowIndex].Cells[0];
bool cb = (bool)cell.EditedFormattedValue;
if (cb)
count++;
else
count--;
if (count > 5)
{
MessageBox.Show("You can only tick 5 items");
((DataGridView)sender).CancelEdit();
}
else
this.dataGridView1.Tag = count;
}
}
Points to note
-: The
CellContentClick
event can be fired when the DGV is being populated, which is why I check for
IsCurrentRowDirty
-: cell.Value doesn't return the value that you are moving the checkbox to, despite the fact you can "see" that it has been ticked. So use
EditedFormattedValue
instead
-: If you don't use
.CancelEdit()
then the checkbox remains ticked!