Question

I have a DataGridView with a CheckBox column in it. (This is an inventory system.) The check is used to move serial numbers of items from one location to another in our company.

I also have a textbox where, as of now, the employee enters the number of items he is moving, then checks the appropriate serial numbers, and moves the items.

I would like the number in the textbox to be generated depending on how many serial numbers are checked. Is it even possible? I've tried about a hundred different solutions at this point and they all either end in strange errors, or give me no results whatsoever.

Was it helpful?

Solution

Untested, but this should be close enough. I read an article or ten about this once when I was having the same issue. The trick is to commit the edit immediately when the box is clicked on, which will then trigger the CellValueChanged event. You can then pick up the count from there.

This should update the textbox as you check and uncheck the checkbox:

private void dgv_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
    if (dgv.IsCurrentCellDirty && dgv.CurrentCell.OwningColumn.Name == "MyCheckColumn")
        dgv.CommitEdit(DataGridViewDataErrorContexts.Commit);
}

private void dgv_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    if (e.RowIndex == -1) //just a guard for the header row
        return;

    if (dgv.Columns[e.ColumnIndex].Name == "MyCheckColumn")
        textBox.Text = dgv.Rows.Cast<DataGridViewRow>().Count(r => Convert.ToBoolean(r.Cells["MyCheckColumn"].Value)).ToString();
}

Hopefully the Linq works. If not, you'll have to do it the old-fashioned foreach way with a sum variable. I know the DataGridViewRowCollection can be finicky sometimes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top