我有一个带有两个datagridviews的C#应用程序,我想要第一个数据网格来计算位置,并将它放在第二个datagridview中 .
例如:这是我的第一个datagrid InputDataGrid
:
Position | Description | Value
-------------------------------
001 | test | 2,5
002 | | 1
001 | hello | 1,5
002 | test2 | 2
如果我点击一个按钮,我希望这个数据在第二个数据网格中的形式 - > ResultDataGrid
Position | Value
----------------
001 | 4
002 | 3
这是我的代码: UPDATE
private void btnCalc_Click(object sender,EventArgs e){
foreach (DataGridViewRow row in InputDataGrid.Rows)
{
if (row.Cells[0].Value == null)
{
break;
}
string position = (string)row.Cells[0].Value;
Double sellvalue = Convert.ToDouble(row.Cells[2].Value);
foreach (DataGridViewRow resultrow in ResultDatagrid.Rows)
{
if ((string)resultrow.Cells[0].Value == position)
{
Double oldvalue = Convert.ToDouble(resultrow.Cells[1].Value);
Double newValue = oldvalue + sellvalue;
resultrow.Cells[0].Value = Convert.ToString(newValue);
}
else
{
resultrow.Cells[0].Value = position;
resultrow.Cells[1].Value = Convert.ToString(sellvalue);
ResultDatagrid.Rows.Add(resultrow);
}
}
}
}
2 回答
它有点复杂,但有效:
我认为最简单的原因是使用linq只用几行代码对
DataGridView
的底层数据源执行求和操作,然后将结果用作另一个网格的数据源: