Paul Reed
Paul Reed

Reputation: 123

DataGridView and CheckBoxes

I'm making an application which has a page with a button and a datagridview inside.

The data comes from MySQL and the population is done this way:

this.ObjectsTable.Rows.Add(Objects.GetValue(index, 0), 
                           Objects.GetValue(index, 1), 
                           Objects.GetValue(index, 2), 
                           Objects.GetValue(index, 3));

The problem:

I cannot check the checkbox. Literally. When I click it it just goes to "pressed/onPress" state but never goes "checked".

How to fix that? And how to get the row whose checkbox was checked? I want to make an array and then iterate through them.

Upvotes: 0

Views: 629

Answers (1)

gzaxx
gzaxx

Reputation: 17590

First check if your DataGridView is either Enabled or is not ReadOnly, if that did not help check if the Column is not read only.

Second part of you question answer depends if you want to immediately know which CheckBox has been checked or not. Is yes then use this event:

private void GridCellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    if (e.RowIndex < 0 || e.ColumnIndex < 0)
    {
        return;
    }

    if (dataGridView1[e.ColumnIndex, e.RowIndex] is DataGridViewCheckBoxCell)
    {
        var check = (dataGridView1[e.ColumnIndex, e.RowIndex].Value as bool?) ?? false;

        if (check)
        {
            //checked
        }
    }
}

or just iterate through all rows and check value of cell with checkbox:

foreach (DataGridViewRow row in dataGridView1.Rows)
{
      var check = (row.Cells[0].Value as bool?) ?? false;
}

Upvotes: 1

Related Questions