Here's the scenario.
I have checkbox
(Name:"Check All" ID:chkItems) and datagridview
. And when I click on this checkbox, all checkboxes on the datagridview
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;
}
}
}
The code is under _CellContentClick, the the line before message box is checking if the clicked/ selected checkbox is unchecked..if the selected checkbox is not yet checked the message box will pop but if the checkbox is checked already the message box will pop up..Then when i hit NO the clicked/checked checkbox will ...
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
}
private void setCheckBoxInDataGrid(DataGridView dgv, int pos, bool isChecked)
{
for (int i = 0; i < dgv.RowCount; i++)
{
dgv.Rows[i].DataGridView[pos, i].Value = isChecked;
}
}
This is how I did it
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With