0

I am trying to update the value of a checkbox column in datagridview in c# by code but it is not working. Here it is the code:

public frmShowData()
{
    InitializeComponent();
    dgvAlumnos.AutoGenerateColumns = false;
    dgvAlumnos.ReadOnly = false;
    updateAttendance();
}
public void updateAttendace(){
    foreach (DataGridViewRow r in dgvAlumnos.Rows)
    {
        if (attendance[r.Index] == true)
        {
            r.Cells[2].Value = true;
        }
        else
        {
            r.Cells[2].Value = false;
        }
    }
}

Attendance is the array of booleans where I have the values.

The column number 2 of the datagridview is the checkbox column.

However, the changes are not visible in the datagriview. I am using this code inside the form construct.

Thanks in advance.

  • What is the underlying source of the datagrid? you typically have to change the source, then the datagrid should update itself – CitrusO2 Jun 21 '21 at 08:00
  • btw, `if` statements like these can be simplified -> you do not need an if to begin with: `r.Cells[2].Value = attendance[r.Index];` – CitrusO2 Jun 21 '21 at 08:03
  • [How to detect DataGridView CheckBox event change?](https://stackoverflow.com/questions/11843488/how-to-detect-datagridview-checkbox-event-change) – dr.null Jun 21 '21 at 13:53
  • I suggest you copy/paste the actual code as opposed to re-typing the code to avoid typing errors. For starters, In the form’s constructor, the method `updateAttendance();` will not be found because the method below is spelled differently. – JohnG Jun 21 '21 at 17:47
  • In addition, the code in the constructor is a little confusing. Is what is missing is “where” in the constructor is the grid filled with data? From the posted code, on the last line of the constructor, when the code calls the `updateAttendance()` method… the `foreach` loop will never be entered since the grid has no rows. Unless there is something you are not showing, it makes sense that nothing is updated. – JohnG Jun 21 '21 at 17:48

2 Answers2

0

Try using value = true instead.

foreach (DataGridViewRow r in dgvAlumnos.Rows)
{
    if (attendance[r.Index] == true)
    {
        r.Cells[2].Value = true;
    }
    else
    {
        r.Cells[2].Value = false;
    }
}
Thomson Mixab
  • 657
  • 4
  • 8
0

Try these two after changing data

dgvAlumnos.RefreshEdit();
dgvAlumnos.Refresh();