0
  foreach (DataGridViewRow dgvr in dataGridViewProductList.Rows)
                {
                    string dgvrID = dgvr.Cells["ID"].Value.ToString();
                    DataRow[] s = DT.Select("BillID = " + dgvrID);
                    if (s.Length > 0)
                    {
                        dataGridViewProductList.Columns["chk"].ReadOnly = false;
                        dataGridViewProductList.Rows[dgvr.Index].Cells["chk"].ReadOnly = false;
                         dataGridViewProductList.Rows[dgvr.Index].Cells["chk"].Value = 1;
        }
    }

after running code DataGridViewCheckBoxCell doesn't changed to checked, how can i change its checked state

i tried

DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)dataGridViewProductList.Rows[dgvr.Index].Cells["chk"];
                         cell.ReadOnly = false;
                        cell.TrueValue = true;

                        cell.Value = cell.TrueValue;

but doesn't work.

Manu Varghese
  • 791
  • 8
  • 25

1 Answers1

1

A suggestion is to try this. Before you set the true/false value, check to see if cell.Value is null. If it is, then set it with cell.Value = true; or cell.Value = false; NOT cell.Value = cell.TrueValue/FalseValue; The code below is supposed to toggle (check/un-check) each checkbox in column 3 on a button click. If the check box is null I set it to true. If I use cell.Value = cell.TrueValue; when its null it doesn’t work.

Just a Thought.

private void button1_Click(object sender, EventArgs e)
{
  foreach (DataGridViewRow row in dataGridView1.Rows)
  {
    DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)row.Cells[2];
    if (cell.Value != null)
    {
      if (cell.Value.Equals(cell.FalseValue))
      {
        cell.Value = cell.TrueValue;
      }
      else
      {
        cell.Value = cell.FalseValue;
      }
    }
    else
    {
      //cell.Value = cell.TrueValue; // <-- Does not work here when cell.Value is null
      cell.Value = true;
    }
  }
}

A more compact version to toggle check box values - removed check for false value.

if (cell.Value.Equals(cell.FalseValue))

This if will never get entered because a check box that is not checked will return a null cell.Value, and this will therefore be caught by the previous if(cell.Value != null). In other words... if its not null... its checked.

private void button1_Click(object sender, EventArgs e)
{
  foreach (DataGridViewRow row in dataGridView1.Rows)
  {
    DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)row.Cells[2];
    if (cell.Value != null)
    {
      cell.Value = cell.FalseValue;
    }
    else
    {
      //cell.Value = cell.TrueValue; // <-- Does not work here when cell.Value is null
      cell.Value = true;
    }
  }
}

Hope this helps.

JohnG
  • 9,259
  • 2
  • 20
  • 29