Can someone help me why it doesn\'t work?
I have a checkbox
and if I click on it,
this should uncheck all the checkbox inside the datagridview which were check
You can use this code on your grid CellClick event for check or unchecked cell checkbox :
private void Grid_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 0)
{
Grid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = (Grid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value == null ? true : (!(bool)Grid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value));
}
}
I had the same problem, and even with the solutions provided here it did not work. The checkboxes would simply not change, their Value would remain null. It took me ages to realize my dumbness:
Turns out, I called the form1.PopulateDataGridView(my data)
on the Form derived class Form1 before I called form1.Show()
. When I changed up the order, that is to call Show()
first, and then read the data and fill in the checkboxes, the value did not stay null.
The code bellow allows the user to un-/check the checkboxes in the DataGridView, if the Cells are created in code
private void gvData_CellClick(object sender, DataGridViewCellEventArgs e)
{
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)gvData.Rows[e.RowIndex].Cells[0];
if (chk.Value == chk.TrueValue)
{
gvData.Rows[e.RowIndex].Cells[0].Value = chk.FalseValue;
}
else
{
gvData.Rows[e.RowIndex].Cells[0].Value = chk.TrueValue;
}
}
// here is a simple way to do so
//irate through the gridview
foreach (DataGridViewRow row in PifGrid.Rows)
{
//store the cell (which is checkbox cell) in an object
DataGridViewCheckBoxCell oCell = row.Cells["Check"] as DataGridViewCheckBoxCell;
//check if the checkbox is checked or not
bool bChecked = (null != oCell && null != oCell.Value && true == (bool)oCell.Value);
//if its checked then uncheck it other wise check it
if (!bChecked)
{
row.Cells["Check"].Value = true;
}
else
{
row.Cells["Check"].Value = false;
}
}