Datagridview error. System.IndexOutOfRangeException: ‘Index 1 does not have a value.’

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

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật