【问题标题】:Get value from DataGridViewCheckBoxCell从 DataGridViewCheckBoxCell 中获取值
【发布时间】:2012-11-29 18:43:25
【问题描述】:

我正在开发一个名为ListingGridDataGridView,试图激活/停用已在DataGridViewCheckBoxColumn 内的任何DataGridViewCheckBoxCell 上“检查”的用户。

这就是我尝试这样做的方式:

foreach (DataGridViewRow roow in ListingGrid.Rows)
{
    if ((bool)roow.Cells[0].Value == true)
    {
        if (ListingGrid[3, roow.Index].Value.ToString() == "True")
        {
            aStudent = new Student();
            aStudent.UserName = ListingGrid.Rows[roow.Index].Cells[2].Value.ToString();
            aStudent.State = true;
            studentList.Add(aStudent);

        }
    }
}

据我所知,当您检查DataGridViewCheckBoxCell 时,单元格的值是true 对吗?但它不允许我将值转换为 bool 然后比较它,这会抛出一个无效的强制转换异常。

【问题讨论】:

标签: c# winforms


【解决方案1】:

尝试:

DataGridViewCheckBoxCell chkchecking = roow.Cells[0] as DataGridViewCheckBoxCell;

    if (Convert.ToBoolean(chkchecking.Value) == true)
{
}

DataGridViewCheckBoxCell chkchecking = roow.Cells[0] as DataGridViewCheckBoxCell;

        if ((bool)chkchecking.Value == true)
    {
    }

【讨论】:

  • “作为 DataGridViewCheckBoxCell;”效果很好,谢谢!
  • 即使它可以工作,也无需转换为 DataGridViewCheckBoxCell。您可以简单地执行“Convert.ToBoolean(roow.Cells[0].Value);”
  • 第一个解决方案对我有用,第二个没有。可能是什么问题呢?只是好奇。
  • 这仅适用于我添加行code var senderGrid = (DataGridView)sender; codesenderGrid.EndEdit();在检查值之前(请参阅link
【解决方案2】:

我认为== true 没有用,您必须检查您的单元格是否不是DBNull

if (chkchecking.Value != DBNull.Value)

【讨论】:

    【解决方案3】:

    我通常这样做 bool value = (short)chkchecking.Value == 1

    【讨论】:

      【解决方案4】:

      尝试了不同的选项,相同的代码有时有效,有时无效。经过大量调试,发现根本原因不是复选框获取代码,而是 datagridvew 机制本身。

      active/selected 行中复选框的值从未正确接收。如果datagridview只有一行,则无法检测到此问题。

      myDataGridViewName.EndEdit();
      

      这必须在读取单元格值之前调用。之后,批准答案中的简单陈述就足够了。

      Convert.ToBoolean(chkchecking.Value)
      

      (bool)chkchecking.Value
      

      两者都按预期工作。此提示的功劳归于另一个 answer 的类似问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-07
        • 2021-10-26
        • 1970-01-01
        相关资源
        最近更新 更多