Last Week I'm Working On A WinFroms Project And I Created A Cart Form.
In Cart, There Is A DataGridView Control & It Contains A Column Named purchasedQuantity.
purchasedQuantity Is Editable & User Can Enter Value Only In This Column. Here Is The EvenHandler For CellEndEdit
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;
}
}
The Problem Is That Whenever I Click On Any Cell Of The DataGridView, I Get The Following Error:
An unhandled exception of type 'System.IndexOutOfRangeException' occurred in System.Windows.Forms.dll
Additional information: Index -1 does not have a value.
Make sure that the maximum index on a list is less than the list size
Make sure the index is not a negative number.
Make sure data column names are correct.
I Have A Home Form That Create ViewProduct Form Instance And That ViewProduct Form Creates Cart Form Instance & I Get Error In The Home Form In The Following Function:
Home => ViewProdcuts => Cart
private void ShowForm(Form form)
{
this.Hide();
form.ShowDialog();
form.Close();
this.Show();
}
On The Following Line:
form.ShowDialog();
As I Mentioned First, I Start Working On It Last Week. At That Time It Works Fine, No Exceptions Are Thrown On Clicking On Any Row & I Was Able To Enter Value In The purchasedQuanttiy Cell.
After One Week It Get Angry, Don't Know Why (Just Kidding)
I Googled That Problem But Found No Answer. Can Anybody Please Tell Me What Is Wrong With This Code.
Thanks In Advance For Reply