Visual Studio 当单击datagridview复选框时进行求和

mi7gmzs6  于 2023-01-21  发布在  其他
关注(0)|答案(1)|浏览(128)
private void grid_games_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    int total = 0;
    for (int i = 0; i <= grid_games.RowCount - 1; i++)
    {
        Boolean chek = Convert.ToBoolean(grid_games.Rows[i].Cells[0].Value);
        if (chek)
        {
            total += 1;
        }
    }
    total *= 50;
    txt_total.Text = total.ToString();
}

我需要对从DataGridView选择框中选择的每一行进行求和。每一行值为50。它正在工作,但有延迟,因此当我单击2 check时,它只向我显示50...当我取消选中一个框时,也会发生同样的延迟。我如何通过单击该复选框立即获得总数?

pokxtpni

pokxtpni1#

DataGridView控件的CheckBox列由DataGridViewCheckBoxCell类实现,该类具有延迟功能,即当用户在DataGridView中选中一个CheckBox时,会延迟一段时间将其更新到数据源。
只需添加一个关于CurrentCellDirtyStateChanged的事件即可立即获取状态

private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            if (this.dataGridView1.IsCurrentCellDirty)
            {
                this.dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
            }
        }

最适合与CellValueChanged一起使用:

private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            int total = 0;
            for (int i = 0; i <= dataGridView1.RowCount - 1; i++)
            {
                Boolean chek = Convert.ToBoolean(dataGridView1.Rows[i].Cells[0].Value);
                if (chek)
                {
                    total += 1;
        }
    }
            total *= 50;
            textBox1.Text = total.ToString();
        }

相关问题