Home > Software design >  do a sum when clicking on the datagridview checkbox
do a sum when clicking on the datagridview checkbox

Time:01-19

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();
}

I need to do a sum for each row selected from the datagridview selection box. each line is worth 50. it is working, but it has a delay, so when I click on 2 check, it only shows me 50... and the same delay occurs when I uncheck a box. how can i instantly get the total by clicking on that checkbox?

CodePudding user response:

The CheckBox column of the DataGridView control is implemented by the DataGridViewCheckBoxCell class, and this class has a delay function, that is, when the user selects a CheckBox in the DataGridView, it will delay updating it to the data source for a period of time.

You just need to add an event about CurrentCellDirtyStateChanged to get the state immediately

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

Best used with 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();
        }
  • Related