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 checked before including the user selected checkbox.
Here is the code:
private void chkItems_CheckedChanged(object sender, EventArgs e)
{
foreach (DataGridViewRow row in datagridview1.Rows)
{
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[1];
if (chk.Selected == true)
{
chk.Selected = false;
}
else
{
chk.Selected = true;
}
}
}
the checkbox should not be selected. it should be checked.
here is the added column
DataGridViewCheckBoxColumn CheckboxColumn = new DataGridViewCheckBoxColumn();
CheckBox chk = new CheckBox();
CheckboxColumn.Width = 20;
datagridview1.Columns.Add(CheckboxColumn);
The code you are trying here will flip the states (if true then became false vice versa) of the checkboxes irrespective of the user selected checkbox because here the
foreach
is selecting eachcheckbox
and performing the operations.To make it clear, store the
index
of the user selected checkbox before performing theforeach
operation and after theforeach
operation call the checkbox by mentioning the stored index and check it (In your case, make itTrue
-- I think).This is just logic and I am damn sure it is correct. I will try to implement some sample code if possible.
Modify your
foreach
something like this:The above function makes all the checkboxes true including the user selected CheckBox. I think this is what you want..
All of the casting causes errors, nothing here I tried worked, so I fiddled around and got this to work.
I was making my own version of a Checkbox to control a DataGridViewCheckBoxColumn when I saw this post wasn't actually answered. To set the checked state of a DataGridViewCheckBoxCell use:
For anyone else trying to accomplish the same thing, here is what I came up with.
This makes the two controls behave like the checkbox column in Gmail. It keeps functionality for both mouse and keyboard.
Looking at this MSDN Forum Posting it suggests comparing the Cell's value with Cell.TrueValue.
So going by its example your code should looks something like this:(this is completely untested)
Edit: it seems that the Default for Cell.TrueValue for an Unbound DataGridViewCheckBox is null you will need to set it in the Column definition.
This code is working note setting the TrueValue and FalseValue in the Constructor plus also checking for null:
While all the other answers are correct, I'll add another simple option which worked for me:
Compressed:
As long as
cIndex
refers to a cell that is of typeDataGridViewCheckBoxCell
, this will work fine. Hope this helps somone.Below Code is working perfect
Select / Deselect a check box column on data grid by using checkbox CONTROL