How do I toggle the background color of a datagridview row with checkbox column?
I have a datagridview bound to a dataset. I added a datagridview checkbox column to it. I want to toggle the background color of a selected row when I select/unselect the checkbox. How do I do it?
Kirtan PatelPosted Aug 14, 2009, 11:01 AM
Dot Forget to mark "do you like answer" please :) it will give me some credit :)
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
foreach (DataGridViewRow r in dataGridView1.Rows)
{
if (Convert.ToBoolean(r.Cells[0].Value) == true)
{
dataGridView1.Rows[r.Index].DefaultCellStyle.BackColor =Color.Red;
}
else
{
dataGridView1.Rows[r.Index].DefaultCellStyle.BackColor = Color.Empty;
}
}
// Make only CheckBox column writable and rest of all Readonly
foreach (DataGridViewColumn c in dataGridView1.Columns)
{
if (c.Index == 0)
{
c.ReadOnly = false;
}
else
{
c.ReadOnly = true;
}
}
}
JesupriyanPosted Aug 14, 2009, 3:48 AM
Henry VuongPosted Sep 19, 2008, 6:00 PM
private void DataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
bool selected = !Convert.ToBoolean(dataGridView1.Rows[e.RowIndex].Cells["ckb_column"].Value);
if (selected)
{
dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Gray;
dataGridView1.Rows[e.RowIndex].Cells["ckb_column"].Value =
!Convert.ToBoolean(dataGridView1.Rows[e.RowIndex].Cells["ckb_column"].Value);
}
else
{
dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.White;
dataGridView1.Rows[e.RowIndex].Cells["ckb_column"].Value =
!Convert.ToBoolean(dataGridView1.Rows[e.RowIndex].Cells["ckb_column"].Value);
}
}
where "ckb_column" is the name of the checkbox column. No need to change the "RowTemplate" property. And of course, I add this to the Form_Load even:
//Delegate the CellClick event
dataGridView1.CellClick +=
new DataGridViewCellEventHandler(DataGridView1_CellClick);
Thank you for answering
Ryan AlfordPosted Sep 19, 2008, 11:13 AM
now, in the "CellClick" event for the DataGridView, add this code.
--------- Code --------
// this will work if your checkbox is the first column in the grid
// if your checkbox is another column, you will need to change the "Cells" index to the correct column index
// This will allow the clicking of any cell in the grid and will "check" the checkbox if it is not checked, and will uncheck
// the checkbox if it is checked.
if (Convert.ToBoolean(dataGridView1.Rows[e.RowIndex].Cells[0].Value))
{
dataGridView1.Rows[e.RowIndex].Cells[0].Value = false;
dataGridView1.Rows[e.RowIndex].Selected = false;
}
else
{
dataGridView1.Rows[e.RowIndex].Cells[0].Value = true;
dataGridView1.Rows[e.RowIndex].Selected = true;
}
--------- Code --------