【问题标题】:Check/Uncheck a checkbox on datagridview选中/取消选中 datagridview 上的复选框
【发布时间】:2012-11-12 05:33:20
【问题描述】:

有人可以帮助我为什么它不起作用吗? 我有一个checkbox,如果我点击它, 这应该取消选中 datagridview 中的所有复选框,这些复选框在包含用户选择的复选框之前已被选中。

代码如下:

        private void chkItems_CheckedChanged(object sender, EventArgs e)
        {
            foreach (DataGridViewRow row in datagridview1.Rows)
            {
                DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[1];
                if (chk.Selected == true)
                {
                    chk.Selected = false;
                }
                else
                {
                    chk.Selected = true;
                }
            }
        }

不应选中复选框。应该检查一下。

这是添加的列

            DataGridViewCheckBoxColumn CheckboxColumn = new DataGridViewCheckBoxColumn();
            CheckBox chk = new CheckBox();
            CheckboxColumn.Width = 20;
            datagridview1.Columns.Add(CheckboxColumn);

【问题讨论】:

  • 你想要一个检查未选中行和取消选中已选中行的反转函数吗?
  • 提示:不要忘记调用datagridview1.EndEdit() 否则检查的值将不会正确显示在事件处理程序中。

标签: c# winforms datagridview datagridviewcheckboxcell


【解决方案1】:

看看这个MSDN Forum Posting,它建议将单元格的值与Cell.TrueValue 进行比较。

因此,通过它的示例,您的代码应该如下所示:(这是完全未经测试的)

编辑:似乎未绑定 DataGridViewCheckBox 的 Cell.TrueValue 的默认值为空,您需要在列定义中进行设置。

private void chkItems_CheckedChanged(object sender, EventArgs e)
{
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[1];
        if (chk.Value  == chk.TrueValue)
        {
            chk.Value = chk.FalseValue;
        }
        else
        {
            chk.Value = chk.TrueValue;
        }
    }
}

此代码是在构造函数中设置 TrueValue 和 FalseValue 以及检查 null 的工作说明:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        DataGridViewCheckBoxColumn CheckboxColumn = new DataGridViewCheckBoxColumn();
        CheckboxColumn.TrueValue = true;
        CheckboxColumn.FalseValue = false;
        CheckboxColumn.Width = 100;
        dataGridView1.Columns.Add(CheckboxColumn);
        dataGridView1.Rows.Add(4);
    }

    private void chkItems_CheckedChanged(object sender, EventArgs e)
    {
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
            if (chk.Value == chk.FalseValue || chk.Value == null)
            {
                chk.Value = chk.TrueValue;
            }
            else
            {
                chk.Value = chk.FalseValue;
            }

        }
        dataGridView1.EndEdit();
    }
}

【讨论】:

  • 我试过这个,但它也没有选中所有复选框。
  • @user1647667 表示它正在检查其中一些?
  • 当我点击分隔的复选框时。它将检查 datagridview 中的所有复选框。
  • @user1647667 我知道这就是您想要的,我的问题是我的示例是否检查了任何内容?
  • @Mr_Green 在他的一个 cmets 中,他提到了一个单独的复选框,这就是我处理它的方式。主要问题是,由于该列没有数据绑定,因此没有为 TrueValue 和 FalseValue 设置值,因此我们正在检查 null。
【解决方案2】:

当我看到这篇文章实际上没有得到答复时,我正在制作我自己的 Checkbox 版本来控制 DataGridViewCheckBoxColumn。要设置 DataGridViewCheckBoxCell 的选中状态,请使用:

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    dataGridView1.Rows[row.Index].SetValues(true);
}

对于尝试完成同样事情的其他人,这就是我想出的。

这使得这两个控件的行为类似于 Gmail 中的复选框列。它保留了鼠标和键盘的功能。

using System;
using System.Windows.Forms;

namespace Check_UnCheck_All
{
    public partial class Check_UnCheck_All : Form
    {
        public Check_UnCheck_All()
        {
            InitializeComponent();
            dataGridView1.RowCount = 10;
            dataGridView1.AllowUserToAddRows = false;
            this.dataGridView1.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dgvApps_CellContentClick);
            this.dataGridView1.CellMouseUp += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.myDataGrid_OnCellMouseUp);
            this.dataGridView1.CellValueChanged += new System.Windows.Forms.DataGridViewCellEventHandler(this.myDataGrid_OnCellValueChanged);
            this.checkBox1.Click += new System.EventHandler(this.checkBox1_Click);
        }

        public int chkInt = 0;
        public bool chked = false;

        public void myDataGrid_OnCellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == dataGridView1.Rows[0].Index && e.RowIndex != -1)
            {
                DataGridViewCheckBoxCell chk = dataGridView1.Rows[e.RowIndex].Cells[0] as DataGridViewCheckBoxCell;

                if (Convert.ToBoolean(chk.Value) == true) chkInt++;
                if (Convert.ToBoolean(chk.Value) == false) chkInt--;
                if (chkInt < dataGridView1.Rows.Count && chkInt > 0)
                {
                    checkBox1.CheckState = CheckState.Indeterminate;
                    chked = true;
                }
                else if (chkInt == 0)
                {
                    checkBox1.CheckState = CheckState.Unchecked;
                    chked = false;
                }
                else if (chkInt == dataGridView1.Rows.Count)
                {
                    checkBox1.CheckState = CheckState.Checked;
                    chked = true;
                }
            }
        }
        public void myDataGrid_OnCellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
        {
            // End of edition on each click on column of checkbox
            if (e.ColumnIndex == dataGridView1.Rows[0].Index && e.RowIndex != -1)
            {
                dataGridView1.EndEdit();
            }
            dataGridView1.BeginEdit(true);
        }
        public void dgvApps_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dataGridView1.CurrentCell.GetType() == typeof(DataGridViewCheckBoxCell))
            {
                if (dataGridView1.CurrentCell.IsInEditMode)
                {
                    if (dataGridView1.IsCurrentCellDirty)
                    {
                        dataGridView1.EndEdit();
                    }
                }
                dataGridView1.BeginEdit(true);
            }
        }
        public void checkBox1_Click(object sender, EventArgs e)
        {
            if (chked == true)
            {
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
                    if (chk.Value == chk.TrueValue)
                    {
                        chk.Value = chk.FalseValue;
                    }
                    else
                    {
                        chk.Value = chk.TrueValue;
                    }
                }
                chked = false;
                chkInt = 0;
                return;
            }
            if (chked == false)
            {
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    dataGridView1.Rows[row.Index].SetValues(true);
                }
                chked = true;
                chkInt = dataGridView1.Rows.Count;
            }
        }
    }
}

【讨论】:

    【解决方案3】:

    简单的代码就可以了

    private void dgv_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        if (dgv.CurrentRow.Cells["ColumnNumber"].Value != null && (bool)dgv.CurrentRow.Cells["ColumnNumber"].Value)
        {
            dgv.CurrentRow.Cells["ColumnNumber"].Value = false;
            dgv.CurrentRow.Cells["ColumnNumber"].Value = null;
        }
        else if (dgv.CurrentRow.Cells["ColumnNumber"].Value == null )
        {
            dgv.CurrentRow.Cells["ColumnNumber"].Value = true;
        }
    }
    

    【讨论】:

      【解决方案4】:

      您在此处尝试的代码将翻转复选框的状态(如果为真则变为假,反之亦然),而与 用户选择的复选框无关,因为这里 foreach选择 每个checkbox 并执行操作。

      为了清楚起见,在执行foreach操作之前存储用户选择复选框的index,在foreach操作之后通过提及存储的索引来调用复选框并检查它(在你的情况下,设为True——我认为)。

      这只是逻辑,我确信它是正确的。如果可能,我会尝试实现一些示例代码。

      像这样修改你的foreach

          //Store the index of the selected checkbox here as Integer (you can use e.RowIndex or e.ColumnIndex for it).
          private void chkItems_CheckedChanged(object sender, EventArgs e)
          {
              foreach (DataGridViewRow row in datagridview1.Rows)
              {
                  DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[1];
                  if (chk.Selected == true)
                  {
                      chk.Selected = false;
                  }
                  else
                  {
                      chk.Selected = true;
                  }
              }
          }
          //write the function for checking(making true) the user selected checkbox by calling the stored Index
      

      上面的函数使所有的复选框都为真,包括用户选择的 CheckBox。我想这就是你想要的..

      【讨论】:

      • 它有效。但是如果我不希望它被选中并且我希望它被选中怎么办。
      • 使用chk.Checked 而不是chk.Selected
      • chk.Checked 有错误。 “DataGridViewCheckBoxCell 不包含“已检查”我将如何处理?
      • @Mr_Green 不幸的是,这不是DataGridViewCheckBox 的选项
      • @MarkHall 是的,我通过查看您的帖子对其进行了编辑。我认为它现在应该可以工作了。
      【解决方案5】:

      试试下面的代码,它应该可以工作

      private void checkBox2_CheckedChanged(object sender, EventArgs e) 
      {
          if (checkBox2.Checked == false)
          {
              foreach (DataGridViewRow row in dGV1.Rows)
              {
                  DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
                  chk.Value = chk.TrueValue;
              }
          }
         else if (checkBox2.Checked == true)
          {
              foreach (DataGridViewRow row in dGV1.Rows)
              {
                  DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
                  chk.Value = 1;
                  if (row.IsNewRow)
                  {
                      chk.Value = 0;
                  }
              }
          }
      }
      

      【讨论】:

        【解决方案6】:

        下面的代码运行完美

        使用复选框 CONTROL 选择/取消选择数据网格上的复选框列

            private void checkBox2_CheckedChanged(object sender, EventArgs e)
            {
                if (checkBox2.Checked == false)
                {
                    foreach (DataGridViewRow row in dGV1.Rows)
                    {
                        DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
        
                            chk.Value = chk.TrueValue;
                    }
               }
               else if(checkBox2.Checked==true)
               {
                    foreach (DataGridViewRow row in dGV1.Rows)
                    {
                        DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
                        chk.Value = 1;
                        if (row.IsNewRow)
                        {
                            chk.Value = 0;
                        }
                    }
                }
            }
        

        【讨论】:

          【解决方案7】:

          您可以在网格 CellClick 事件中使用此代码来选中或未选中单元格复选框:

          private void Grid_CellClick(object sender, DataGridViewCellEventArgs e)
              {
                  if (e.ColumnIndex == 0)
                  {
                      Grid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = (Grid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value == null ? true : (!(bool)Grid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value));
                  }
              }
          

          【讨论】:

            【解决方案8】:

            虽然所有其他答案都是正确的,但我将添加另一个对我有用的简单选项:

            var r = dataGridView.Rows[rIndex];
            var c = r.Cells[cIndex];
            var value = (bool) c.Value; 
            c.Value = !value;
            

            压缩:

            var r = dataGridView.Rows[rIndex];
            r.Cells[cIndex].Value = !((bool) r.Cells[cIndex].Value)
            

            只要cIndex 引用DataGridViewCheckBoxCell 类型的单元格,就可以正常工作。希望这对某人有所帮助。

            【讨论】:

              【解决方案9】:

              你可以试试这个代码:

              DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)dataGridView1.CurrentRow.Cells[0];
                              dataGridView1.BeginEdit(true);
                              if (chk.Value == null || (int)chk.Value == 0)
                              {
                                  chk.Value = 1;
                              }
                              else
                              {
                                  chk.Value = 0;
                              }
                              dataGridView1.EndEdit();
              

              【讨论】:

                【解决方案10】:
                // here is a simple way to do so
                
                //irate through the gridview
                            foreach (DataGridViewRow row in PifGrid.Rows)
                            {
                //store the cell (which is checkbox cell) in an object
                                DataGridViewCheckBoxCell oCell = row.Cells["Check"] as DataGridViewCheckBoxCell;
                
                //check if the checkbox is checked or not
                                bool bChecked = (null != oCell && null != oCell.Value && true == (bool)oCell.Value);
                
                //if its checked then uncheck it other wise check it
                                if (!bChecked)
                                {
                                    row.Cells["Check"].Value = true;
                
                                }
                                else
                                {
                                    row.Cells["Check"].Value = false;
                
                                }
                            }
                

                【讨论】:

                  【解决方案11】:

                  我遇到了同样的问题,即使使用此处提供的解决方案也无法正常工作。复选框根本不会改变,它们的值将保持为空。我花了很长时间才意识到自己的愚蠢:

                  原来,我在 Form 派生类 Form1 上调用了 form1.PopulateDataGridView(my data)之前我调用了 form1.Show()。当我改了顺序,即先调用Show(),然后读取数据并填写复选框,值没有保持为空。

                  【讨论】:

                    【解决方案12】:

                    如果单元格是在代码中创建的,则下面的代码允许用户取消/选中 DataGridView 中的复选框

                    private void gvData_CellClick(object sender, DataGridViewCellEventArgs e)
                    {
                        DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)gvData.Rows[e.RowIndex].Cells[0];
                    
                        if (chk.Value == chk.TrueValue)
                        {
                            gvData.Rows[e.RowIndex].Cells[0].Value = chk.FalseValue;
                        }
                        else
                        {
                            gvData.Rows[e.RowIndex].Cells[0].Value = chk.TrueValue;
                        }
                    
                    }
                    

                    【讨论】:

                      【解决方案13】:

                      这是另一个你可以尝试的例子

                      private void dataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
                          {
                              if (e.ColumnIndex == dataGridView.Columns["Select"].Index)
                              {
                                  dataGridView.EndEdit();
                      
                                  if ((bool)dataGridView.Rows[e.RowIndex].Cells["Select"].Value)
                                  {
                                      //-- checking current select, needs to uncheck any other cells that are checked
                                      foreach(DataGridViewRow row in dataGridView.Rows)
                                      {
                                          if (row.Index == e.RowIndex)
                                          {
                                              dataGridView.Rows[row.Index].SetValues(true);
                                          }
                                          else
                                          {
                                              dataGridView.Rows[row.Index].SetValues(false);
                                          }
                                      }
                                  }
                              }
                          }
                      

                      【讨论】:

                        【解决方案14】:

                        所有的转换都会导致错误,我在这里尝试过没有任何工作,所以我摆弄了一下,让它工作了。

                          foreach (DataGridViewRow row in dataGridView1.Rows)
                                {
                                    if (row.Cells[0].Value != null && (bool)row.Cells[0].Value)
                                    {
                                        Console.WriteLine(row.Cells[0].Value);
                                    }
                        
                                }
                        

                        【讨论】:

                          【解决方案15】:

                          我使用 CellMouseUp 事件。 我检查正确的列

                          if (e.ColumnIndex == datagridview.Columns["columncheckbox"].Index)
                          

                          我将实际单元格设置为 DataGridViewCheckBoxCell

                          dgvChkBxCell = datagridview.Rows[e.RowIndex].Cells[e.ColumnIndex] as DataGridViewCheckBoxCell;
                          

                          然后检查是否使用EditingCellFormattedValue进行检查

                          if ((bool)dgvChkBxCell.EditingCellFormattedValue) { }
                          

                          您必须使用 KeyUp 事件检查键盘输入并检查 .value 属性,并检查 CurrentCell 的列索引是否与复选框列匹配。该方法不提供 e.RowIndex 或 e.ColumnIndex。

                          【讨论】:

                            【解决方案16】:

                            清除选择后对我有用,开始编辑并更改 girdview 行并结束编辑模式。

                             if (dgvDetails.RowCount > 0)
                                                {
                                                    dgvDetails.ClearSelection(); 
                                                    dgvDetails.BeginEdit(true); 
                                                  
                                                    foreach (DataGridViewRow dgvr in dgvDetails.Rows)
                                                    {
                                                        dgvr.Cells["cellName"].Value = true;
                                                    }
                                                    dgvDetails.EndEdit();
                                                }
                            

                            【讨论】:

                              【解决方案17】:

                              我就是这样做的。

                              private void Grid_CellClick(object sender, DataGridViewCellEventArgs e)
                              {
                              
                                  if(Convert.ToBoolean(this.Grid.Rows[e.RowIndex].Cells["Selected"].Value) == false)
                                  {
                                      this.Grid.Rows[e.RowIndex].Cells["Selected"].Value = true;
                                  }
                                  else
                                  {
                                      this.productSpecGrid.Rows[e.RowIndex].Cells["Selected"].Value = false;
                                  }
                              }
                              

                              【讨论】:

                                猜你喜欢
                                • 1970-01-01
                                • 2017-01-24
                                • 1970-01-01
                                • 2012-10-27
                                • 1970-01-01
                                • 1970-01-01
                                • 1970-01-01
                                • 1970-01-01
                                • 2019-09-09
                                相关资源
                                最近更新 更多