Reputation: 1294
I was unable to count checked checkboxes in DataGridView. I want to count the checked checkboxes during the checkbox is checked and store the number of checked items in a label. I tried the following code but does not give the correct count:
int num = 0;
private void dgvLoadData_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
bool isChecked = Convert.ToBoolean(dgvLoadData.Rows[dgvLoadData.CurrentCell.RowIndex].Cells[0].Value.ToString());
if (isChecked)
{
num+=1;
}
else
{
num-=1;
}
labelSelectedSum.Text = "Selected Items: " + num;
}
Upvotes: 3
Views: 11154
Reputation: 1294
Apply CurrentCellDirtyStateChanged
event on the table. Call gridview.CommitEdit
to update value of the checkbox column. Do the following:
private void dgvLoadData_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (dgvLoadData.IsCurrentCellDirty)
{
dgvLoadData.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}
That will call _CellValueChanged
event. No changes will be done on the codes inside CellValueChanged
event:
int num = 0;
private void dgvLoadData_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex < 0)
return;
bool isChecked = (bool)dgvItemsToShip.Rows[e.RowIndex].Cells[0].Value;
if (isChecked)
{
num+=1;
}
else
{
num-=1;
}
labelSelectedSum.Text = "Selected Items: " + num;
}
Upvotes: 4
Reputation: 2129
I have a DataTable bound to my DataGridView and I check if the first column has any checkbox checked Here is my example :
private void dataGridViewMain_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 0)
{
int numberOfRow = dataTableCsvFile.AsEnumerable().Count(r => r[0].ToString() == true.ToString());
buttonDataGridviewVerify.Enabled = numberOfRow > 0;
}
}
Upvotes: 0
Reputation: 41
You can use the event: CellContentClick and CellContentDoubleClick:
Good Luck!
int num = 0;
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
bool isChecked = (bool)dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].EditedFormattedValue;
CheckCount(isChecked);
}
private void dataGridView1_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
{
bool isChecked = (bool)dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].EditedFormattedValue;
CheckCount(isChecked);
}
private void CheckCount(bool isChecked)
{
if (isChecked)
{
num++;
}
else
{
num--;
}
labelSelectedSum.Text = "Selected Items: " + num;
}
Upvotes: 0