0

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

我想搜索数据网格,如果第一列有匹配项,则增加 Cells[6].Value(The number of items),然后使用 Cells[3].Value 中的价格找到总数,然后设置 Cells [6].Value(total) 对这两者的乘积

  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)
    {

    }


}
4

1 回答 1

1

看起来这对你有用:

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;
}
于 2013-10-19T08:27:24.220 回答