Waseem Senjer
Waseem Senjer

Reputation: 1048

How to change the value of DataGridView Cell when another cell in the same row changed?

enter image description here

I want to change the Amount cell when Qty or Price changed.

Amount = Qty * Price

I tried this code and it's always giving me ArgumentOutOfRangeException .

private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (dg_invoices_items.Columns[e.ColumnIndex].Name == "qty")
            {   
                dg_invoices_items[e.RowIndex, 4].Value =Convert.ToString(
                        Convert.ToInt32(dg_invoices_items[e.RowIndex, 2].Value) *
                        Convert.ToInt32(dg_invoices_items[e.RowIndex, 3].Value));
            }
        }

Upvotes: 0

Views: 7509

Answers (2)

Mang
Mang

Reputation: 23

I had the same issue. It works as below

dgvInvoice["TOTAL", e.RowIndex].Value = Convert.ToInt32(dgvInvoice["QUANTITY", e.RowIndex].Value.ToString()) * Convert.ToInt32(dgvInvoice["U_PRICE", e.RowIndex].Value.ToString());

Upvotes: 0

MrFox
MrFox

Reputation: 5126

Column indexes start at 0, your column indexes are one too high.

  • 1st column: 0, Product
  • 2nd column: 1, Qty
  • 3rd column: 2, Price
  • 4th column: 3, Amount

To avoid this you can probably use named columns:

dg_invoices_items["Qty", e.RowIndex].Value = Convert.ToString(
     Convert.ToInt32(dg_invoices_items["Price", e.RowIndex].Value) *
     Convert.ToInt32(dg_invoices_items["Amount", e.RowIndex].Value));

Altough I cannot test any code at the moment, so this might not work.

Upvotes: 2

Related Questions