简体   繁体   中英

Getting 2 values of cell in datagridview

I have two datagridviews. datagridview1 and datagridview2 . When I add a product from datagridview1 to datagridview2 the quantity of the product in datagridview1 is transferred to datagridview2 . Now when I remove a product from datagridview2 I need it to transfer the quantity back to datagridview1 .

在此处输入图片说明

Here is my code.:

private void btnRemove_Click(object sender, EventArgs e)
    {

        int ind = findIndexForItem(dgvPOScart.CurrentRow.Cells[0].Value.ToString());

        int dgvCARTquantity = Convert.ToInt32(dgvPOScart.CurrentRow.Cells[4].Value.ToString());
        int dgvPOSquantity = Convert.ToInt32(dgvPOScart.Rows[ind].Cells[5].Value.ToString());     
        int dgvnewADDquantity;

        dgvnewADDquantity = dgvPOSquantity + dgvCARTquantity;

        foreach (DataGridViewRow item in this.dgvPOScart.SelectedRows)
        {    
            dgvPOScart.Rows.RemoveAt(item.Index);         
        }

    }

And the code for the helper:

        private int findIndexForItem(string name)
    {
        int ind = -1;
        for (int i = 0; i < dgvPOSproduct.Rows.Count; i++)
        {
            if (dgvPOSproduct.Rows[i].Equals(name))
            {
                ind = i;
                break;
            }
        }
        return ind;                
    } 

How can I properly call ind? Rows[ind] ind? Rows[ind] is wrong because ind is the product ID or value or cell[0] and not row index. Or is there an easier way to do this?

Your code is a little weird, you are foreach-ing the SelectedRows but you're only calculating the new quantity for the current row, why?

Also, you shouldn't look at the products by their name since you have their ID (which is more unique than a name).

In order for this to work, you'll need something like this:

private void btnRemove_Click(object sender, EventArgs e)
{
    foreach (var row in dgvPOScart.SelectedRows)
    {
        // Get the row in dgvProducts and the quantity he'll gain back
        var productRow = dgvPOSproduct.Rows[FindRowIndexByID(row.Cells[0].Value)];
        int qtyToAdd = Convert.ToInt32(row.Cells[4].Value);

        // Add the quantity back
        productRow.Cells[5].Value = Convert.ToInt32(productRow.Cells[5].Value) + qtyToAdd;
    }
}

private int FindRowIndexByID(string id)
{
    for (int i = 0; i < dgvPOSproduct.Rows.Count; i++)
    {
        if (dgvPOSproduct.Rows[i].Cells[0].Value == id)
        {
            return i;
        }
    }

    return -1;               
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM