Ishan Sasanka
Ishan Sasanka

Reputation: 19

Datagridview math operation with next row data

I have datagridview with 7 columns. But its not bind to any database. Rows will be added from few textboxes line by line when i press the "Add" button on my form. But i have a problem with my 6th column data(Cells[5]).

current row 6th column data value = next row 2nd column value - current row 2nd column value

I can do this with excel very easily. but how can i do this on a datagridview? codes are welcome.

here is my code.

    private void FEAdd_Click(object sender, EventArgs e)
   {
       int n = dgvFE.Rows.Add();
       dgvFE.Rows[n].Cells[0].Value = dateTimePicker1.Value.ToString("dd-MM-yyyy");
       dgvFE.Rows[n].Cells[1].Value = MtrtextBox1.Text.ToString();
       dgvFE.Rows[n].Cells[3].Value = PltrtextBox11.Text.ToString();
       dgvFE.Rows[n].Cells[4].Value = BvtextBox12.Text.ToString();

       foreach (DataGridViewRow row in dgvFE.Rows)
       {
           dgvFE.Rows[row.Index].Cells[2].Value = Math.Round((Double.Parse(dgvFE.Rows[row.Index].Cells[4].Value.ToString()) / Double.Parse(dgvFE.Rows[row.Index].Cells[3].Value.ToString())), 2).ToString();

           if (n >1)
           {
               dgvFE.Rows[row.Index-1].Cells[5].Value = Math.Round((Double.Parse(dgvFE.Rows[row.Index].Cells[1].Value.ToString()) - Double.Parse(dgvFE.Rows[row.Index-1].Cells[1].Value.ToString())), 2).ToString();
           }

       }

   }

I get below error,

An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll

Additional information: Index was out of range. Must be non-negative and less than the size of the collection.

Upvotes: 0

Views: 478

Answers (2)

ASh
ASh

Reputation: 35646

dgvFE.Rows[row.Index-1] throws exception for row №0. so add an index check

private void FEAdd_Click(object sender, EventArgs e)
{
   int n = dgvFE.Rows.Add();
   dgvFE.Rows[n].Cells[0].Value = dateTimePicker1.Value.ToString("dd-MM-yyyy");
   dgvFE.Rows[n].Cells[1].Value = MtrtextBox1.Text.ToString();
   dgvFE.Rows[n].Cells[3].Value = PltrtextBox11.Text.ToString();
   dgvFE.Rows[n].Cells[4].Value = BvtextBox12.Text.ToString();

   foreach (DataGridViewRow row in dgvFE.Rows)
   {
       row.Cells[2].Value = Math.Round((Double.Parse(row.Cells[4].Value.ToString()) / Double.Parse(row.Cells[3].Value.ToString())), 2).ToString();

       if (n > 0 && row.Index > 0)
       {
           dgvFE.Rows[row.Index-1].Cells[5].Value = Math.Round((Double.Parse(row.Cells[1].Value.ToString()) - Double.Parse(dgvFE.Rows[row.Index-1].Cells[1].Value.ToString())), 2).ToString();
       }

   }
}

Upvotes: 0

Med.Amine.Touil
Med.Amine.Touil

Reputation: 1235

You have 5 column and you write cells[5]. it must be cells[4].

Upvotes: 0

Related Questions