【问题标题】:how to determine which cells in a datagridview are checked?如何确定检查 datagridview 中的哪些单元格?
【发布时间】:2013-04-15 14:01:17
【问题描述】:

我的 datagridview 有 2 列。 列 0 包含处于关闭位置的复选框(默认)。用户可以单击该框并更改状态或选中。

如何循环并找到已检查的内容。这是我的代码

try
{
   // This line will cause InvalidCastException
   // Specified cast is not valid.
   if ((bool)(row.Cells[0]).Value || (CheckState)row.Cells[0].Value == CheckState.Checked)
   {
      // Do something
      MessageBox.Show("Checked");
   }
}
catch (NullReferenceException nre)
{
   MessageBox.Show("No Rows Have Been Checked");
}

【问题讨论】:

    标签: c# checkbox datagridview datagridcell


    【解决方案1】:

    怎么样:

    foreach(DataGridViewRow row in dataGridView.Rows){
        if (row.Cells[0].Value != null && (bool)row.Cells[0].Value){
           //checked, do something
        }
    }
    

    【讨论】:

    • 我对此进行了测试。我有编号为 1 -> 10 的单元格。我检查了 1、2、3,然后创建了一个新列表并将它们添加到列表中。我的新列表只包含 1,2。 3 不见了
    • 如果我将 Value 改为 State,它永远不会进入循环
    • 我的编辑只是格式化了代码。但是尝试将(bool)(row.Cells[0]).Value 更改为(bool)row.Cells[0].Value
    【解决方案2】:

    this answer的单线:

    List<DataGridViewRow> list = DataGridView1.Rows.Cast<DataGridViewRow>().Where(k => Convert.ToBoolean(k.Cells[CheckBoxColumn1.Name].Value) == true).ToList();
    

    这将为您提供选中复选框的所有行的列表。

    【讨论】:

    • CheckBoxColumn1.Name,这是列的索引还是实际名称?
    • 那是栏目名称
    • 我从来没有那样使用过列表。有没有一种简单的方法可以使用您的 1 衬垫来获取所有被选中的行,并使用选定的行是 datagridview 的新数据源(因此只显示已检查的行)。
    • This question 将是开始深入研究的好地方
    • 我已经设法将 List 用于我的数据源。我了解到 Datasourec 会寻找属性。所以我必须创建一个名为 StringValue 的类,它是一个具有接受字符串的构造函数和返回字符串值的 Value 方法的类。但是我是否需要使用 DataGridRow 作为我的数据源来做同样的事情,还是它会自动工作?
    猜你喜欢
    • 2012-05-15
    • 1970-01-01
    • 1970-01-01
    • 2014-07-19
    • 1970-01-01
    • 1970-01-01
    • 2011-08-21
    • 1970-01-01
    相关资源
    最近更新 更多