user1647667 user1647667 - 2 months ago 14
C# Question

Check All Checkbox items on DataGridView

here's the scenario,

i have checkbox(Name:Check All ID:chkItems) and datagridview. And when i click on the checkbox. All checkbox on the gridview will also be checked.

I've also added the checkbox column on the grid.

DataGridViewCheckBoxColumn CheckboxColumn = new DataGridViewCheckBoxColumn();
CheckBox chk = new CheckBox();
CheckboxColumn.Width = 20;
GridView1.Columns.Add(CheckboxColumn);


Here is the code behind of the checkbox. there is a problem on the row.Cell

private void chkItems_CheckedChanged(object sender, EventArgs e)
{
foreach (DataGridViewRow row in GridView1.Rows)
{
DataGridViewCheckBoxCell chk = e.row.Cells(0);
if (chk.Selected == false)
{
row.Cells(0).Value = true;
}
}
}


SOLVED (here is the solution)

private void chkItems_CheckedChanged(object sender, EventArgs e)
{
foreach (DataGridViewRow row in GridView1.Rows)
{
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[1];
if (chk.Selected == false)
{
chk.Selected = true;
}
}
}

Answer
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell) row.Cells[0];

instead of

DataGridViewCheckBoxCell chk = e.row.Cell(0);

*EDIT:*I think you really want to do this:

foreach (DataGridViewRow row in dataGridView1.Rows)
{
       DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell) row.Cells[0];
       chk.Value = !(chk.Value == null ? false : (bool) chk.Value); //because chk.Value is initialy null
}
Comments