Hossein Mahmoodi
Hossein Mahmoodi

Reputation: 117

Unable to check or uncheck DataGridViewCheckBoxColumn cells programmatically

I'm trying to change DataGridViewCheckBoxColumn's items via this code

        foreach (DataGridViewRow dgvUser in UsersGrid.Rows)
        {
          dgvUser.Cells["ChkSelect"].Value = true;
        }

the value of checkboxs changed but the checkboxs on UI stay uncheck.

How to do it ?

Upvotes: 2

Views: 4370

Answers (3)

Beth Smith
Beth Smith

Reputation: 1

I had this exact problem when I tried clearing other checkbox columns in the same row (performed within the CellValueChanged method). To fix my issue, I needed the following code:

private void dgv_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    // filter for valid DataGridViewCheckBoxCell columns, if desired
    dgv.CommitEdit(DataGridViewDataErrorContexts.Commit);
}

Upvotes: 0

Edmondo
Edmondo

Reputation: 20080

The problem here is that the DataGridViewCheckboxCell acts differently from other cells. For some reason, the property which is used to determine how the checkbox should be drawn (checked or unchecked) is not Value but FormattedValue

My feeling though is that that the Value setter has been overriden in DataGridViewCheckBoxCell to act correctly. So if you call it on a DataGridViewCell you are using the base one (which does not affect FormattedValue) while if you cast the cell things should work:

((DataGridViewCheckBoxCell)  dgvUser.Cells["ChkSelect"]).Value = true;

Upvotes: 1

Nitin Gupta
Nitin Gupta

Reputation: 202

You need to update the Datagridview and Refresh then.

DataGrid_ABC.Update(); in order to update the changes in the gridview

Upvotes: 1

Related Questions