Winform dataGridView cells proble

Viewed 30

I have a DataGridView in a Winform desktop project in net 6.0 This DataGridView's generic row is composed by a DataGridViewCheckBoxCell in the first column, and another 6 DataGridViewTextBoxCells in the subsequent columns : the first one of the DataGridViewTextBOxCell (column 1) is permanently ReadOnly. What I want to do is make the Cells from the second TextBox to the last one (that is columns 2 to 6) ReadOnly when the CheckBox is unchecked, and restore them to ReadWrite when the checkbox is checked. What I do is override the dataGridViev.CellClick event, and when the sender is the element in column 0 (the checkbox) I get the row index and I iterate on the cells of the row from index 2 to 6 and set the ReadOnly property to true or false depending on the state of the checkobx itself. The mechanism basically works fine, I read the event on the exact column/row, I correctly get the state of the checkobox (maybe in a not-so-smart way...) : but when it comes to setting the ReadOnly property I can see that ,in spite of iterating on the 2 to 6 column, it skips the cell in column 2 and sets the one in column 1 instead: all the settings on the other columns work correctly. I thought it was a matter of configuring the columns in the designer but all the columns from 2 to 6 are set identically. My event handler is the following :

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0) // if checkbox
            {
                int row = e.RowIndex;
                bool setState = true;
                DataGridViewCheckBoxCell check = (DataGridViewCheckBoxCell)(dataGridView1.Rows[row].Cells[0]);
                if (check.Value != null && check.Value == "true")
                {
                    setState = true;
                    check.Value = "false";// CheckState.Unchecked;
                }
                else
                {
                    setState = false;
                    check.Value = "true";// CheckState.Checked;
                }
                for (int i = 2; i < dataGridView1.Rows[row].Cells.Count; i++)
                {
                    DataGridViewTextBoxCell txt = (DataGridViewTextBoxCell)(dataGridView1.Rows[row].Cells[i]);
                    txt.ReadOnly = setState; 
                    if (setState) txt.Style.BackColor = Color.Gray;
                    else txt.Style.BackColor = Color.White;
                } 
             }
        }
0 Answers
Related