The CurrentCellDirtyStateChanged event code will limit the number of checkboxes to (2). The rows with checked boxes contain editable data that is used to calculate values in the remaining unchecked readonly rows. I would like the datagrid to indicate editable rows by changing the color of the checked rows and have the remaining rows be readonly. The CurrentCellDirtyStateChanged event works for managing the checkboxes, but conflicts with the CellClick event for changing the row color. The boxes do not check and change color consistently. Any help would be greatly appreciated.
using System.Linq;
private void dgvParameters_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (dgvParameters.CurrentCell is DataGridViewCheckBoxCell && dgvParameters.IsCurrentCellDirty && !(bool)dgvParameters.CurrentCell.FormattedValue)
{
var count = dgvParameters.Rows.Cast<DataGridViewRow>()
.SelectMany(r => r.Cells.OfType<DataGridViewCheckBoxCell>()
.Where(c => (bool)c.FormattedValue))
.Count();
if (count == 2) dgvParameters.CancelEdit();
}
}
private void dgvParameters_CellClick(object sender, DataGridViewCellEventArgs e)
{
int index = dgvParameters.CurrentRow.Index;
DataGridViewCellStyle CheckedStyle;
DataGridViewCellStyle UnCheckedStyle;
CheckedStyle = new DataGridViewCellStyle();
UnCheckedStyle = new DataGridViewCellStyle();
CheckedStyle.BackColor = Color.White;
CheckedStyle.ForeColor = Color.Black;
UnCheckedStyle.BackColor = Color.LightGray;
UnCheckedStyle.ForeColor = Color.Black;
bool isSelect = dgvParameters[5, index].Value as bool? ?? false;
if (Convert.ToBoolean(row.Cells[5].Value))
{
dgvParameters.Rows[index].Cells[1].Style = CheckedStyle;
dgvParameters.Rows[index].Cells[3].Style = CheckedStyle;
dgvParameters.Rows[index].Cells[1].ReadOnly = false;
dgvParameters.Rows[index].Cells[3].ReadOnly = false;
}
else
{
dgvParameters.Rows[index].Cells[1].Style = UnCheckedStyle;
dgvParameters.Rows[index].Cells[3].Style = UnCheckedStyle;
dgvParameters.Rows[index].Cells[1].ReadOnly = true;
dgvParameters.Rows[index].Cells[3].ReadOnly = true;
}
}
