【问题标题】:how to change DataGridViewCheckBoxCell checked state by code如何通过代码更改 DataGridViewCheckBoxCell 选中状态
【发布时间】:2016-11-26 06:38:57
【问题描述】:
  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;
        }
    }

运行代码DataGridViewCheckBoxCell 后没有更改为选中状态,我该如何更改其选中状态

我试过了

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

                        cell.Value = cell.TrueValue;

但不起作用。

【问题讨论】:

  • cell.Value = CheckState.Checked;
  • cell.Value = CheckState.Checked; 它对我不起作用@bansi
  • 值类型为布尔型:.Value = true
  • @Slai 不起作用

标签: c# .net winforms datagridview datagridviewcheckboxcell


【解决方案1】:

一个建议是试试这个。在设置真/假值之前,请检查cell.Value 是否为空。如果是,则将其设置为cell.Value = true; or cell.Value = false; NOT cell.Value = cell.TrueValue/FalseValue; 下面的代码应该在单击按钮时切换(选中/取消选中)第 3 列中的每个复选框。如果复选框为空,我将其设置为true。如果我在 cell.Value = cell.TrueValue; 为 null 时使用它,则它不起作用。

只是一个想法。

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;
    }
  }
}

用于切换复选框值的更紧凑的版本 - 删除了对错误值的检查。

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

这个 if 永远不会被输入,因为未选中的复选框将返回 null cell.Value,因此这将被之前的 if(cell.Value != null) 捕获。换句话说......如果它不为空......它被选中。

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;
    }
  }
}

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2016-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-22
    • 2012-10-01
    • 1970-01-01
    • 2016-12-14
    • 1970-01-01
    相关资源
    最近更新 更多