Emilia
Emilia

Reputation: 49

DataGridView Edit only 1 row in the column

I have an home work i almost finished it all but i could not get this one this is my data grid view columns

Name , Price , Quantity , Total , button(to increase) , button (to decrease)

in the data Grid View i made a button when i double click on the increase button the quantity will increase by 1 every time so i made this code to that

foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            row.Cells["Qty"].Value = Convert.ToDouble(row.Cells["Add"].Value) + Convert.ToDouble(row.Cells["Qty"].Value) + 1;
        }

but it do the Entire column if i have 2 rows when i double click on it the quantity of both rows is increasing how can i change that code to just 1 row for the button

Upvotes: 1

Views: 617

Answers (2)

PandaPlayer
PandaPlayer

Reputation: 171

the problem is the foreach.
in the button event you need to get the row index.
You can get the row index with

 var index = datagridview.CurrentCell.RowIndex;

Than you can do something like this:

dataGridView1.Rows[index].Cells["Qty"].Value = 
Convert.ToDouble(dataGridView1.Rows[index].Cells["Add"].Value) 
+ Convert.ToDouble(dataGridView1.Rows[index].Cells["Qty"].Value) + 1;

Upvotes: 1

EylM
EylM

Reputation: 6103

You are looping over all rows with for statement.

You should use the CurrentCell.RowIndex property to get the current selected row.

So you code should look like:

var row = dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex];
row.Cells["Qty"].Value = Convert.ToDouble(row.Cells["Add"].Value) + Convert.ToDouble(row.Cells["Qty"].Value) + 1;

Upvotes: 2

Related Questions