【问题标题】:Count checked checkboxes in a DataGridView via Linq通过 Linq 计算 DataGridView 中选中的复选框
【发布时间】:2019-12-01 23:09:36
【问题描述】:

下面的代码给了我这个错误:https://prnt.sc/q4truq

    private void Form1_Load(object sender, EventArgs e)
    {
        MyDataGridView.Columns.Insert(0, new DataGridViewCheckBoxColumn());
        MyDataGridView.Rows.Add(4);
        MyDataGridView.Rows[0].Cells[0].Value = true;
        MyDataGridView.Rows[1].Cells[0].Value = false;
        MyDataGridView.Rows[2].Cells[0].Value = true;
        MyDataGridView.Rows[3].Cells[0].Value = false;
        MyDataGridView.Rows[4].Cells[0].Value = true;

        string strResults = (MyDataGridView.Rows.Cast<DataGridViewRow>()
                           .Where(c => Convert.ToBoolean(r.Cells[0].Value).Equals(true))
                           .Count(s => Convert.ToInt32(t.Cells[0].Value))).ToString();
    }

【问题讨论】:

  • 这很容易研究。您在 WinForms 版本的哪个部分遇到问题?
  • 您在这里遇到什么问题?如果您想要选中复选框的总数,那么您可以使用 Count linq 方法而不是 Sum 方法。
  • var count = dataGridView1.Rows.Cast&lt;DataGridViewRow&gt;().Where(r =&gt; Convert.ToBoolean(r.Cells["NameOrIndexOfCheckColumn"].Value)).Count();
  • @JQSOFT 非常感谢。解决了。​​
  • 非常欢迎。祝你好运。

标签: c# winforms linq checkbox datagridview


【解决方案1】:

这个错误是因为已经没有名为 r 的变量但是有 c 所以这是你的解决方案我的朋友 ^_^

        private void Form1_Load(object sender, EventArgs e)
        {
            MyDataGridView.Columns.Insert(0, new DataGridViewCheckBoxColumn());
            MyDataGridView.Rows.Add(4);
            MyDataGridView.Rows[0].Cells[0].Value = true;
            MyDataGridView.Rows[1].Cells[0].Value = false;
            MyDataGridView.Rows[2].Cells[0].Value = true;
            MyDataGridView.Rows[4].Cells[0].Value = true;

            int strResults = MyDataGridView.Rows.Cast<DataGridViewRow>()
                           .Where(c => Convert.ToBoolean(c.Cells[0].Value).Equals(true)).ToList().Count;
            MessageBox.Show("" + strResults);
        }

【讨论】:

  • "" + strResults ?只需使用strResults.ToString()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-10
  • 2012-01-20
  • 2023-03-30
  • 2016-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多