gggg
gggg

Reputation: 25

Check duplicate and sum values in datagridview c#

I'm coding like below but it works incorrect.It perform(plus and delete) only 2->3 rows if data has 5->6 duplicate data.

Update and It works

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--;

                }
            }
        }

enter image description here

Upvotes: 0

Views: 4817

Answers (1)

dotNET
dotNET

Reputation: 35400

This should do the trick for you:

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--;
      }
    }
}

You basically need to keep track of j variable as you remove rows from the collection.

If you're a fan of LINQ and don't mind a bit of a convoluted code, here is another approach:

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--;
    }
}

As a word of advice, this kind of stuff is handled far more easily in the back-end. Whatever your DataGridView is bound to, be it a DataTable or a generic collection, you should implement duplicate removal there instead of directly playing with DataGridView cells.

Upvotes: 1

Related Questions