Search code examples
c#datagridviewcycle

c# datagridview sum cells with same column names (in sequence)


I have a datagridview with one row and a set of columns with two names (like apples and pears). I need to sum the cell values of a row. But, an important nuance is that I need to summarize only the first occurring data of apples and pears (the column can be 1, or there can be several). I tried to show what I mean in screenshots.

Example 1:
Example 1

Example 2:
Example 2

Example 3:
Example 3

I only need to sum the first set of apples and pears that occur. As soon as apples and pears are summed up and the next row is apples again, the loop should end.

How can this be implemented?


Solution

  • you need to create a function and send the keys like: Apples, Pears. function is:

        public int SumFirstOccur(string Key)
        {
            int Sum = 0;
            bool IsFind = false; // if find after next iterative if not found break the loop.
    
            for (int i = 0; i < dgv.Columns.Count; i++)
            {
    
                if (dgv.Columns[i].HeaderText == Key)
                {
                    Sum += Convert.ToInt32(dgv.Rows[0].Cells[i].Value);
                    IsFind = true;
                }
                else if (IsFind)
                {
                    break;
                }
    
            }
            return Sum;
        }
    

    then call function SumFirstOccur("Pears") or SumFirstOccur("Apples") .you can change the function as you need!