1

上周我正在处理一个 WinFroms 项目并创建了一个购物车表单。在购物车中,有一个DataGridView控件,它包含一个名为purchaseQuantity的列。
购买数量是可编辑的,用户只能在此列中输入值。这是CellEndEdit的 EvenHandler

private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e) 
{
    if (e.RowIndex <= 0 || e.ColumnIndex != 4)
        return;

    int row = e.RowIndex;
    int demandedQuantity = int.Parse(this.dataGridView1.Rows[row].Cells["purchasedQuantity"].Value.ToString());
    int inStockQunatity = int.Parse(this.dataGridView1.Rows[row].Cells["unitsInStock"].Value.ToString());
    double price = double.Parse(this.dataGridView1.Rows[row].Cells["unitPrice"].Value.ToString());

    if (demandedQuantity <= inStockQunatity)
    {
        this.dataGridView1.Rows[row].Cells["subTotal"].Value = (demandedQuantity * price).ToString();
        this.dataGridView1.Rows[row].Cells["unitsInStock"].Value = (inStockQunatity - demandedQuantity).ToString();
        this.dataGridView1.Rows[row].Cells["purchasedQuantity"].Style.BackColor = System.Drawing.Color.White;
    }
    else
    {
        MessageBox.Show(string.Format("We Have Only {0} Left In The Stock..!!", inStockQunatity.ToString()), "Error", MessageBoxButtons.OK);
        this.dataGridView1.Rows[row].Cells["purchasedQuantity"].Style.BackColor = System.Drawing.Color.Red;
    }
}

问题是每当我单击 DataGridView 的任何单元格时,都会出现以下错误:

System.Windows.Forms.dll 中出现“System.IndexOutOfRangeException”类型的未处理异常附加信息:索引 -1 没有值。
确保列表上的最大索引小于列表大小
确保索引不是负数。
确保数据列名称正确。

我有一个创建ViewProduct表单实例的主页表单,并且该ViewProduct表单创建了购物车表单实例,我在以下功能的主页表单中遇到错误: 主页 => ViewProdcuts => 购物车

 private void ShowForm(Form form) 
 {
      this.Hide();
      form.ShowDialog();

      form.Close();
      this.Show();
 }

在以下行:

form.ShowDialog();

正如我首先提到的,我上周开始研究它。那时它工作正常,单击任何行都不会引发异常,并且我能够在购买的数量单元格中输入值。
一周后它生气了,不知道为什么(开个玩笑)
我用谷歌搜索了这个问题,但没有找到答案。谁能告诉我这段代码有什么问题。
提前感谢您的回复

4

0 回答 0