Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check All Checkbox items on DataGridView

Here's the scenario.

I have checkbox(Name:"Check All" ID:chkItems) and datagridview. And when I click on this checkbox, all checkboxes on the datagridview will also be checked.

I've also added the checkbox column on the grid.

DataGridViewCheckBoxColumn CheckboxColumn = new DataGridViewCheckBoxColumn();
CheckBox chk = new CheckBox();
CheckboxColumn.Width = 20;
GridView1.Columns.Add(CheckboxColumn);

Here is the code behind of the checkbox. There is a problem on the row.Cell

private void chkItems_CheckedChanged(object sender, EventArgs e)
{
    foreach (DataGridViewRow row in GridView1.Rows)
    {
        DataGridViewCheckBoxCell chk = e.row.Cells(0);
        if (chk.Selected == false)
        {
            row.Cells(0).Value = true;
        }
    }
}   
like image 591
user1647667 Avatar asked Nov 06 '12 00:11

user1647667


People also ask

How to Check and uncheck CheckBox in GridView in vb net?

The code is under _CellContentClick, the the line before message box is checking if the clicked/ selected checkbox is unchecked..if the selected checkbox is not yet checked the message box will pop but if the checkbox is checked already the message box will pop up..Then when i hit NO the clicked/checked checkbox will ...


2 Answers

DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell) row.Cells[0];

instead of

DataGridViewCheckBoxCell chk = e.row.Cell(0);

*EDIT:*I think you really want to do this:

foreach (DataGridViewRow row in dataGridView1.Rows)
{
       DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell) row.Cells[0];
       chk.Value = !(chk.Value == null ? false : (bool) chk.Value); //because chk.Value is initialy null
}
like image 72
Nikola Davidovic Avatar answered Nov 15 '22 23:11

Nikola Davidovic


    private void setCheckBoxInDataGrid(DataGridView dgv, int pos, bool isChecked)
    {
        for (int i = 0; i < dgv.RowCount; i++)
        {
            dgv.Rows[i].DataGridView[pos, i].Value = isChecked;
        }
    }

This is how I did it

like image 43
Elliott Marshall Avatar answered Nov 15 '22 23:11

Elliott Marshall