检查datagridview中的重复值和总和c#
问题描述:
我编码如下,但它工作不正确。如果数据有5-> 6重复数据,它执行(加和删除)只有2-3行。检查datagridview中的重复值和总和c#
更新和它的工作原理
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--;
}
}
}
答
这应该为你做的伎俩:
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
单元格。
它的作品,但我不得不多次点击处理按钮。如果点击一次它的活动就像我的代码。 – gggg
@gggg:哪一个,简单的还是LINQ的版本? – dotNET
我用了简单的版本。 – gggg