I am using 2 bindlist _productList
and _resultList
. _resultList
shows the result of when a barcode is searched. and added to _productList
. _productList
has an option to remove and add using buttons.
When I delete the most recent product in the _productList
it throws and error Index does not have value. I think it is because it is trying to format a index that is not existing since it has been removed from the list if delete button is used. After throwing the error it still does remove the item in the productList but the error is still happens if the most recent item is removed
public CashierDash(EF_DataContext context)
{
InitializeComponent();
_context = context;
_httpClient = new HttpClient();
_resultList = new BindingList<Product_PriceDto>();
_productList = new BindingList<Product_PriceDto>();
dgvResult.AutoGenerateColumns = false;
UpdateTotals();
this.KeyPreview = true;
this.KeyDown += CashierDash_KeyDown;
this.KeyDown -= CashierDash_KeyDown;
txtBarcode.KeyDown += txtBarcode_KeyDown;
txtQuantity.TextChanged += txtQuantity_TextChanged;
_timer = new System.Windows.Forms.Timer();
_timer.Interval = 1000; // Set the interval to 100 milliseconds
_timer.Tick += Timer_Tick; // Attach the event handler
_timer.Start(); // Start the timer
}
private void dgvResult_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
try
{
// Check for valid indices
// Adjust index check with +1
if (e.RowIndex < 0 || e.ColumnIndex < 0 || e.RowIndex >= dgvResult.Rows.Count) return; // Access the current DataGridView row
var row = dgvResult.Rows[e.RowIndex ];
// Ensure the row has a valid DataBoundItem and is of correct type
if (row.DataBoundItem is not Product_PriceDto product) return;
// Adjust column visibility based on DataSource
if (dgvResult.DataSource == _resultList)
{
// Hide specific columns when using _resultList as the DataSource
dgvResult.Columns["LessQuantity"].Visible = false;
dgvResult.Columns["AddQuantity"].Visible = false;
dgvResult.Columns["DeleteProduct"].Visible = false;
// Dynamic quantity from the text box
if (dgvResult.Columns[e.ColumnIndex].Name == "Quantity")
{
e.Value = txtQuantity.Text;
}
else if (dgvResult.Columns[e.ColumnIndex].Name == "GrossPrice")
{
// Try to convert the quantity from txtQuantity and calculate the GrossPrice
if (decimal.TryParse(txtQuantity.Text, out decimal quantity))
{
e.Value = product.ProductPrice * quantity;
}
else
{
e.Value = "Invalid Quantity"; // Handle invalid quantity text
}
}
else if (dgvResult.Columns[e.ColumnIndex].Name == "NetAmount")
{
// Try to convert the quantity and calculate the NetAmount
if (decimal.TryParse(txtQuantity.Text, out decimal quantity))
{
decimal discountPercentage = 0; // Example discount percentage
decimal grossPrice = product.ProductPrice * quantity;
decimal discount = grossPrice * (discountPercentage / 100);
e.Value = grossPrice - discount;
}
else
{
e.Value = "Invalid Quantity"; // Handle invalid quantity text
}
}
}
else if (dgvResult.DataSource == _productList)
{
// Show specific columns when using _productList as the DataSource
dgvResult.Columns["LessQuantity"].Visible = true;
dgvResult.Columns["AddQuantity"].Visible = true;
dgvResult.Columns["DeleteProduct"].Visible = true;
// Static quantity from the product list
if (dgvResult.Columns[e.ColumnIndex].Name == "Quantity")
{
e.Value = product.Quantity;
}
else if (dgvResult.Columns[e.ColumnIndex].Name == "GrossPrice")
{
e.Value = product.ProductPrice * product.Quantity;
}
else if (dgvResult.Columns[e.ColumnIndex].Name == "NetAmount")
{
decimal discountPercentage = 0; // Example discount percentage
decimal grossPrice = product.ProductPrice * product.Quantity;
decimal discount = grossPrice * (discountPercentage / 100);
e.Value = grossPrice - discount;
}
}
}
catch (Exception ex)
{
// Handle any unexpected errors
MessageBox.Show($"An error occurred during cell formatting: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void dgvResult_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex < 0 || e.ColumnIndex < 0 || e.RowIndex >= dgvResult.Rows.Count) return; // Access the current DataGridView row
// Get the product object from the clicked row
var product = dgvResult.Rows[e.RowIndex].DataBoundItem as Product_PriceDto;
// Ensure the product object is valid
if (product == null) return;
// Retrieve the ProductId from the product
int productId = product.ProductId; // Assuming Product_PriceDto contains ProductId
// Fetch the product data from the database based on the ProductId
var productEntity = _context.Product_Price.FirstOrDefault(p => p.ProductId == productId);
if (productEntity == null)
{
MessageBox.Show("Product not found in the database.");
return;
}
// Identify which column was clicked (lessQuantity, addQuantity, or deleteProduct)
var clickedColumnName = dgvResult.Columns[e.ColumnIndex].Name;
// Retrieve the current displayed quantity from the DataGridView cell
if (!int.TryParse(dgvResult.Rows[e.RowIndex].Cells["Quantity"].Value?.ToString(), out int currentDisplayedQuantity))
{
MessageBox.Show("Invalid quantity value.");
return;
}
if (clickedColumnName == "lessQuantity")
{
// Decrease the displayed quantity by 1
if (currentDisplayedQuantity > 1)
{
dgvResult.Rows[e.RowIndex].Cells["Quantity"].Value = currentDisplayedQuantity - 1;
UpdateTotals();
}
else
{
// If the quantity becomes zero, remove the product from the list
_productList.Remove(product);
}
}
else if (clickedColumnName == "addQuantity")
{
// Get the max quantity from the database productEntity
int maxQuantity = productEntity.Quantity; // Assuming productEntity.Quantity holds the max quantity from the database
// Increase the displayed quantity by 1 but do not exceed the maximum allowed in the database
if (currentDisplayedQuantity < maxQuantity)
{
dgvResult.Rows[e.RowIndex].Cells["Quantity"].Value = currentDisplayedQuantity + 1;
UpdateTotals();
}
else
{
MessageBox.Show($"Cannot exceed the maximum quantity of {maxQuantity} for this product.");
}
}
else if (clickedColumnName == "deleteProduct")
{
// Remove the product from the list entirely
_productList.Remove(product);
UpdateTotals();
}
// Refresh the DataGridView to reflect the changes
dgvResult.Refresh();
}
I tried to add a plus one in the index like this
if (e.RowIndex < 0 || e.ColumnIndex < 0 || e.RowIndex +1>= dgvResult.Rows.Count) return;
it does not give me the error Index does not have value anymore but it does not format the datagrid.
I tried to search but I can’t fix my error.
I tried to add this almost everywhere I can think of but it does not help, I thought adding this might refresh the datagrid index count.
dgvResult.Refresh();
It seems that the error only happens if I delete the most recent index from the datagrid.
0