C# .NET - Finding Average in gridView - Asked By s j on 15-Nov-11 04:28 AM



Hi,

I have a grid view where i have to calculate average after unit price reaches 50 and display it in another column.
Means, the user can enter the number of units that he wants to take.
If the count of the units is 50 then i have to show the average value in the next column.
If the count exceeds 50, then the exceeded amount of units is spilt to next row with the same ID as shown below.

How can i do this to show like below in my gridview.


ID (units) TOTAL AVERAGE
 1     10 100
 2 30 300
 3 10 100 50

 4 25 250
 5 20 200
 6 5 50 50

 6 20 200
 7 10 100

  

Cheers,
Samantha.
Kirtan Patel replied to s j on 15-Nov-11 01:09 PM

private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
  if (dataGridView1.Rows.Count > 1)
  {
    /* Assuming Unit Column index is 0 ie Unit Price is in Column1 */
    if (e.ColumnIndex == 0)
    {
      /* Find Total of all Above row */
      int RowIndex = e.RowIndex;
      int RowsCount = e.RowIndex + 1;
      if (RowsCount % 3 == 0)
      {
        
        /* Write Average in Column 2*/
        int val1 = Convert.ToInt32(dataGridView1.Rows[RowIndex].Cells["Unit"].Value);
        int val2 = Convert.ToInt32(dataGridView1.Rows[RowIndex - 1].Cells["Unit"].Value);
        int val3 = Convert.ToInt32(dataGridView1.Rows[RowIndex - 2].Cells["Unit"].Value);

        if ((val1 + val2 + val3) == 50)
        {
          int avg = (val1 + val2 + val3) / 3;
          dataGridView1.Rows[RowIndex].Cells[1].Value = avg;
        }
      }

    }
  }
}