我无法计算DataGridView中的已选中复选框。我想在选中复选框期间计算选中的复选框,并将选中项目的数量存储在标签中。我尝试了以下代码,但没有给出正确的计数:
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;
}
答案 0 :(得分:2)
在表格上应用CurrentCellDirtyStateChanged
个事件。致电gridview.CommitEdit
以更新复选框列的值。执行以下操作:
private void dgvLoadData_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (dgvLoadData.IsCurrentCellDirty)
{
dgvLoadData.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}
这将调用_CellValueChanged
事件。不会对CellValueChanged
事件中的代码进行任何更改:
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;
}
答案 1 :(得分:0)
您可以使用以下事件:CellContentClick和CellContentDoubleClick:
祝你好运!
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;
}
答案 2 :(得分:0)
我有一个DataTable绑定到我的DataGridView,我检查第一列是否有任何复选框选中 这是我的例子:
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;
}
}