【问题标题】:Get value of checkbox in Datagridview?获取Datagridview中复选框的值?
【发布时间】:2017-06-27 14:08:32
【问题描述】:

我试图在 DataGridView 中获取选中复选框的值,所以我检查值是真还是假:

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0 && e.RowIndex != -1)
            {

                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {

                    if ((bool)dataGridView1.Rows[i].Cells["check"].Value == true)
                    {

                        dataGridView1.Rows[i].Cells["check"].Value = false;
                    }
                    else
                    {

                        dataGridView1.Rows[i].Cells["check"].Value = true;
                    }

                    button2.Enabled = (counter > 0);

                }
            }
        }
    } 

它涉及一行错误:

if ((bool)dataGridView1.Rows[i].Cells["check"].Value == true)

第二种解决方案:

 if (dataGridView1.Rows[i].Cells["check"].Value == null || (bool)dataGridView1.Rows[i].Cells["check"].Value == false)
                    {

                        dataGridView1.Rows[i].Cells["check"].Value = true;

                        counter++;
                    }
                    else
                    {

                        dataGridView1.Rows[i].Cells["check"].Value = false;

                        counter--;
                    }

以下代码有效,但有时未选中复选框

【问题讨论】:

标签: c# c#-4.0 datagridview


【解决方案1】:

在我的一个项目中,我正在做一些非常相似的事情, 我只使用 OnCellValueChanged 而不是 CellContentClick。

这是我的工作代码行

bool completed = Convert.ToBoolean(dgv.Rows[e.RowIndex].Cells[1].Value.ToString());

您的错误究竟是什么?您是否尝试查看调试器中的 .Value 是什么?

【讨论】:

  • 再次查看我的问题,我添加了新的解决方案,但它会一次又一次地检查
  • 你的意思是:但有时复选框没有被选中?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-12
  • 2012-07-20
  • 2012-07-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多