Mathieu
Mathieu

Reputation: 4520

Checkbox in datagrid view doesn't update my bindingList

I have a datagrid with 2 columns. One is a checkbox and one is a normal textbox cell. All is bound to one BindingList which is an entity.

If I check one checkbox and then loop to get the checked entities from the BindingList, it returns nothing. But if I check then edit the textbox column, it works just fine and return one result.

I tried to refresh or to check then click somewhere else. It doesn't work.

How do you manage to get your bindingList updated when you check a column?

Thank you!

Upvotes: 0

Views: 1871

Answers (1)

Mitja Bonca
Mitja Bonca

Reputation: 4546

What data type is the column in the data source (dataTable)? Is it boolean type?

But this doesnt matter so much, what matters is that you use the correct event of the dgv. Use: 1. CurrentCellDirtyStateChanged and 2. CellValueChanged

This is the code you have to use:

    private void CreateAndBind()
    {
        DataTable table = GetDataToDataTable();
        //then bind it to dgv:
        dgv.DataSource = new BindingSource(table, null);
        //create events for dgv:
        dgv.CurrentCellDirtyStateChanged += new EventHandler(dgv_CurrentCellDirtyStateChanged);
        dgv.CellValueChanged += new EventHandler(dgv_CellValueChanged);
    }

    private DataTable GetDataToDataTable()
    {
        //get data from dataBase, or what ever...   
        table.Columns.Add("column1", typeof(stirng));
        table.Columns.Add("column2", typeof(bool));

        //adding some exmaple rows:
        table.Rows.Add("item 1", true);
        table.Rows.Add("item 2", false);
        return table;
    }

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

    private void dgv_CellValueChanged(object obj, DataGridViewCellEventArgs e)
    {
        if (e.ColumnIndex == 0) //compare to checkBox column index
        {
            DataGridViewCheckBoxCell check = dataGridView1[0, e.RowIndex] as DataGridViewCheckBoxCell;
            if (Convert.ToBoolean(check.Value) == true)
            {
                //If tick is added!
                //
            }
        }
    }

Hope it helps.

Upvotes: 1

Related Questions