我编码如下,但它的工作原理不正确。如果数据有5> 6个重复数据,它只执行(加号和删除)2行和3行。
更新并运行
for (int i = 0; i < dataGridView1.RowCount - 1; i++) //compare data
{
var Row = dataGridView1.Rows[i];
string abc = Row.Cells[1].Value.ToString() + Row.Cells[2].Value.ToString().ToUpper();
// MessageBox.Show(abc);
for (int j = i + 1; j < dataGridView1.RowCount; j++)
{
var Row2 = dataGridView1.Rows[j];
string def = Row2.Cells[1].Value.ToString() + Row2.Cells[2].Value.ToString().ToUpper();
if (abc == def)
{
Row.Cells[5].Value = Convert.ToDouble(Row.Cells[5].Value.ToString()) + Convert.ToDouble(Row2.Cells[5].Value.ToString());
dataGridView1.Rows.Remove(Row2);
j--;
}
}
}
答案 0 :(得分:1)
这应该适合你:
for (int i = 0; i < dataGridView1.RowCount - 1; i++) //compare data
{
var Row = dataGridView1.Rows[i];
string abc = Row.Cells[0].Value.ToString() + Row.Cells[1].Value.ToString().ToUpper();
for (int j = i+1; j < dataGridView1.RowCount; j++)
{
var Row2 = dataGridView1.Rows[j];
string def = Row2.Cells[0].Value.ToString() + Row2.Cells[1].Value.ToString().ToUpper();
if (abc == def)
{
Row.Cells[2].Value = (int)Row.Cells[2].Value + (int)Row2.Cells[2].Value;
dataGridView1.Rows.Remove(Row2);
j--;
}
}
}
在从集合中删除行时,您基本上需要跟踪j
变量。
如果您是LINQ的粉丝并且不介意一些复杂的代码,这是另一种方法:
for (int i = 0; i < dataGridView1.RowCount; i++) //compare data
{
var R = dataGridView1.Rows[i];
var V = R.Cells[0].Value.ToString() + R.Cells[1].Value.ToString().ToUpper();
var DupRows = dataGridView1.Rows.Cast<DataGridViewRow>().Skip(i + 1).
Where(r => r.Cells[0].Value.ToString() + r.Cells[1].Value.ToString().ToUpper() == V);
R.Cells[2].Value = (int)R.Cells[2].Value + DupRows.Sum(r => (int)r.Cells[2].Value);
foreach (var DupRow in DupRows)
DupRow.Tag = "Del";
}
for (int i = 0; i < dataGridView1.RowCount; i++)
{
var R = dataGridView1.Rows[i];
if (R.Tag?.ToString() == "Del")
{
dataGridView1.Rows.Remove(R);
i--;
}
}
作为建议,这种东西在后端更容易处理。无论您DataGridView
绑定的是DataTable
还是通用集合,都应该在那里实现重复删除,而不是直接使用DataGridView
个单元格。