如何在 C# 中的 DataGridView 中递增该值(如果该值已存在于数据网格中)

本文关键字:于数据 存在 数据 网格 如果 中的 DataGridView | 更新日期: 2023-09-27 18:35:59

我有这段代码,它做了正确的事情,但选择器停留在第一行,所以它增加了错误条目的数量。

我想搜索数据网格,如果第一列有匹配项,则递增单元格[6]。值(项目数),然后使用单元格[3]中的价格找到总数。值然后设置单元格[6]。两者乘积的价值(总计)

  private void productCodeBox_TextChanged(object sender, EventArgs e)//Event that waits for a correct barcode_id to be entered in
{
    string[] itemInfo;//defines a string to hold product information coming in from the API using the getProduct method
    int quantity = 1;//sets the initial quantity to 1 as a default
    try//tries to parse any input in until a correct product code is entered else carries on checking
    {
        itemInfo = getProduct(productCodeBox.Text);//initializes the array with the product code that matches a value in the API
            foreach (DataGridViewRow row in productList.Rows)//used to check if the item is in the data gridview and adds a qty instead of a whole new item
            {
                if (row.Cells[0].Value.ToString().Equals(itemInfo[0]))//checks if the product code is already in the datagridview
                {
                    productList.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
                    //Increments the qty
                    int qty = (int)productList.Rows[productList.CurrentRow.Index].Cells[6].Value;//gets the current value of the quantity field in the DataGridView at the selected position
                    productList.Rows[productList.CurrentRow.Index].Cells[6].Value = qty + 1;//Increments the value of the the quantity column in the datagrid view but only the first value.
                    //Gets the total of that column
                    double price = (double)productList.Rows[productList.CurrentRow.Index].Cells[3].Value;
                    double total = price * qty;//calculates the product
                    productList.Rows[productList.CurrentRow.Index].Cells[7].Value = total;//is meant to get the price from the total column but nothing is displayed
                    itemInfo = null;//resets the array so that the item is not duplicated
                    productCodeBox.Clear();//clears the box to wait for the next input
                } 
            }
            productList.Rows.Add(new object[] { itemInfo[0], itemInfo[1], itemInfo[2], itemInfo[3], itemInfo[4], itemInfo[5], quantity });//inserts the new value if it does not already exist
        productCodeBox.Clear();//clears the text box to wait for more input
    }
    catch(Exception a)
    {
    }

}

如何在 C# 中的 DataGridView 中递增该值(如果该值已存在于数据网格中)

看起来这对你有用:

var matchedRow = productList.Rows.OfType<DataGridViewRow>()
                            .FirstOrDefault(row=>row.Cells[0].Value != null &&
                                                 row.Cells[0].Value.Equals(itemInfo[0]));
if(matchedRow != null){
  int qty = (int)matchedRow.Cells[6].Value + 1;
  double price = (double)matchedRow.Cells[3].Value;
  matchedRow.Cells[7].Value = price * qty;
}