Best way to do this is have a DataSource e.g. in this case a DataTable. In the code below I increase and decrease the Qty value of the current row in the DataGridView.
The BindingSource component provides access to the current row, we cast to a DataRow than use SetField and Field extensions to change values.
Alternate to a DataTable would be a List<T>
namespace DataGridViewDemo
{
public partial class DataGridViewForm : Form
{
private BindingSource bindingSource = new BindingSource();
public DataGridViewForm()
{
InitializeComponent();
Shown += OnShown;
}
private void OnShown(object sender, EventArgs e)
{
dataGridView1.AutoGenerateColumns = false;
DataTable table = new DataTable();
table.Columns.Add("Item", typeof(string));
table.Columns.Add("Qty", typeof(int));
table.Columns.Add("Price", typeof(decimal));
table.Rows.Add("First item", 2, 60);
table.Rows.Add("Second item", 2, 50);
table.Rows.Add("Third item", 1, 20);
bindingSource.DataSource = table;
dataGridView1.DataSource = bindingSource;
}
private void IncreaseButton_Click(object sender, EventArgs e)
{
var row = ((DataRowView)bindingSource.Current).Row;
row.SetField("Qty", row.Field<int>("Qty") +1);
}
private void DecreaseButton_Click(object sender, EventArgs e)
{
var row = ((DataRowView)bindingSource.Current).Row;
row.SetField("Qty", row.Field<int>("Qty") -1);
}
}
}
Source code