hi i have a datagridview whose first column (index = 0) is a checkbox column. i want to update a label when a cell is checked and unchecked. my function seems to work fine, but it doesn’t update the label until the next cell in that column is changed.
when the form loads all rows are checked, so say 4 of 4. i uncheck one row and the label doesn’t update. i uncheck another row and then it says 3, so you see it’s working a step behind.
i’ve tried a few different DataGridViewCellEvents like CellValueChanged, CellStateChanged, CellEndEdit, but they all act the say way. i do still need to have a DataGridViewCellEventArgs e so i can check the column.
any suggestions?
private void fileGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 0)
{
int numberOfFiles = 0;
for (int i = 0; i < fileGrid.Rows.Count; i++)
{
Console.WriteLine(fileGrid[0, i].Value.ToString());
if (fileGrid[0, i].Value.ToString() == "True")
{
numberOfFiles++;
}
}
numberOfFilesLabel.Text = numberOfFiles.ToString();
}
}
i can’t answer my own question yet, but this is what i used to accomplish:
private void fileGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 0)
{
int numberOfFiles = 0;
for (int i = 0; i < fileGrid.Rows.Count; i++)
{
Console.WriteLine(fileGrid[0, i].Value.ToString());
if (fileGrid[0, i].Value.ToString() == "True")
{
numberOfFiles++;
}
}
if (fileGrid.IsCurrentCellDirty)
fileGrid.CommitEdit(DataGridViewDataErrorContexts.Commit);
if (fileGrid.CurrentCell.Value.ToString().Equals("True"))
{
numberOfFiles++;
}
if (fileGrid.CurrentCell.Value.ToString().Equals("False"))
{
numberOfFiles--;
}
numberOfFilesLabel.Text = numberOfFiles.ToString();
}
}
this happens because the edited value is not committed directly after changing the checkbox. its committed, when you leave the editor.
you have to commit the value immediately to get the behaviour you want.
one way i found, but did not try is this one:
EDIT:
demo solution.