【问题标题】:Count values from selected rows from dataGridView计算 dataGridView 中选定行的值
【发布时间】:2015-03-18 21:02:34
【问题描述】:

我正在尝试创建一个 dataGridView,它有 2 列,第 1 列包含名称,第 2 列包含数字,工作正常。

我现在想允许用户使用键盘或鼠标选择单行或多行,这应该会根据所选行自动汇总数字列。

到目前为止,我有以下几点:

    private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        if (dataGridView1.SelectedCells.Count > 0)
        {
            int selectedrowindex = dataGridView1.SelectedCells[0].RowIndex;

            DataGridViewRow selectedRow = dataGridView1.Rows[selectedrowindex];

            string a = Convert.ToString(selectedRow.Cells[0].Value);
        }
    }

string a 最终将在表单的标签中显示总数。

但这似乎是做我想要实现的目标的错误方法。有什么建议吗?

【问题讨论】:

  • 您的代码只显示当前单元格?您想要一个所选数字的总和

标签: c# .net visual-studio-2013 .net-3.5


【解决方案1】:

如果要查找特定列的总选定'的值:

int total = dgv.SelectedRows.Cast<DataGridViewRow>().Sum(
    row => (int) row.Cells[colSomeNumber.Name].Value);

如果要查找所选单元格的总值:

int total = dgv.SelectedCells.Cast<DataGridViewCell>().Sum(cell => (int) cell.Value);

如果您只想查找某些列的所有选定单元格的值,请执行以下操作:

int total = dgv.SelectedCells.Cast<DataGridViewCell>().Where(
    c => c.OwningColumn == colSomeNumber).Sum(cell => (int) cell.Value);

colSomeNumber实际 列。

只需将其放入dgv_SelectionChanged 事件中即可。这几乎是“最简洁”的方式。

【讨论】:

  • 这确实有效,但前提是我单击单元格中的实际内容。如果单击行的任何部分来选择它,我如何让它工作?
  • 目前看起来像这样:this.dataGridView1.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellContentClick); 似乎无法更改 _SelectionChanged
  • SelectionChanged 是另一个事件,可能更适合您的需要。如果您希望它在选定的 rows 上触发,我建议您更改 SelectionMode,例如.SelectionMode = DataGridViewSelectionMode.FullRowSelect; 并使用答案中的第一个解决方案(用户仍然可以编辑单个单元格)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-10
  • 2016-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多