Monday, July 13, 2009

How to highlight rows in a DataGrid using a CheckBox


This is for highlighting rows in a DataGrid using a CheckBox

private void dgvItemsDetails_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (dgvItemsDetails.Columns[selected.Name].Index == e.ColumnIndex)
{
dgvItemsDetails.MultiSelect = true;
if (Convert.ToBoolean(dgvItemsDetails[selected.Name, e.RowIndex].FormattedValue) == true)
{
dgvItemsDetails[selected.Name, e.RowIndex].Value = false;

}
else
{
dgvItemsDetails[selected.Name, e.RowIndex].Value = true;
}
}
int i = 0;
foreach (DataGridViewRow dgvrow in dgvItemsDetails.Rows)
{

if (Convert.ToBoolean(dgvrow.Cells[0].Value.ToString()) == true)
{
SetDataGridViewRowAsHighlighted(dgvItemsDetails, i, true);
}
else
{
SetDataGridViewRowAsHighlighted(dgvItemsDetails, i, false);
}
i++;
}


}

private void SetDataGridViewRowAsHighlighted(DataGridView dgvItemsDetails,int intRowIndex, bool boolIsChecked)
{
if (boolIsChecked == true)
{

dgvItemsDetails.Rows[intRowIndex].Selected = true;
dgvItemsDetails.Rows[intRowIndex].DefaultCellStyle.SelectionBackColor = Color.LightSlateGray;
}
else
{
dgvItemsDetails.Rows[intRowIndex].Selected = false;
dgvItemsDetails.Rows[intRowIndex].DefaultCellStyle.SelectionBackColor = Color.White;
}
}