Search code examples
c#tabcontroldatagridviewcheckboxcell

Set DataGridViewCheckBoxCell on all TabPage tabs


I have a TabControl with on each TabPage a DataGridView. The DataGridView has in Column[0] a DataGridViewCheckBoxCell.

I want to uncheck the DataGridViewCheckBoxes on the same Row of the DataGridView of all the TabPages.

I can only access the DataGridView on the clicked TabPage. It looks like the sender object from the myDataGrid_CellContentClick event doesn't contain the other TabPages.

How can I set the checkBox on the other TabPages.

void myDataGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        int clickedRow = e.RowIndex;
        int clickedColumn = e.ColumnIndex;
        if (clickedColumn != 0) return;
        DataGridView myDataGridView = (DataGridView)sender;

        if (!ToggleAllRowSelection)
        {
            foreach (TabPage myTabPage in tabControl1.TabPages)
            {
                foreach (DataGridViewRow myRow in myDataGridView.Rows)
                {
                    if (myRow.Index == clickedRow)
                    {
                       ((DataGridViewCheckBoxCell)myRow.Cells[0]).Value = false;
                    }

                }
            }
        }

    }

Solution

  • If every TabPage contains a different DataGrid then you need to reference the appropriate grid, select the matching row and check the cell

    void myDataGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        int clickedRow = e.RowIndex;
        int clickedColumn = e.ColumnIndex;
        if (clickedColumn != 0) return;
        DataGridView myDataGridView = (DataGridView)sender;
    
        if (!ToggleAllRowSelection)
        {
            foreach (TabPage myTabPage in tabControl1.TabPages)
            {
                DataGridView grd = myTabPage.Controls.OfType<DataGridView>().FirstOrDefault();
                if(grd != null)
                {
                    grd.Rows[clickedRow].Cells[0].Value  = false;
                }
            }
        }
    }
    

    It is very important to note that this code assumes that you have only one grid per page and every grid contains the same amount of rows as the one clicked.