bretddog bretddog - 1 month ago 6
C# Question

Delete list item with BindingNavigator, not correct item

I use a BindingNavigator to delete items from the products list, via the datagridview. (The methodcall main.DeleteProduct() calls a repository to delete from database).

I need some help to improve the code of the ..DeleteItem_Click event. When I click on a cell/or row, and then delete button (BindingNavigator), it never deletes that row. It deletes the row below, or if it's the last row, the row above, and if only one row, a null is cast. Shouldn't the bindingSource.Current be same item as currentrow of datagridview?

Also, is the way I'm casting the current item using the bindingsource a good way? Would appretiate better code suggestion if you have.

Cheers!

public partial class Form1 : Form
{
private MainBL main = new MainBL();
private List<Product> products = new List<Product>

private void Form1_Load(object sender, EventArgs e)
{

bsProducts.DataSource = products; // BindingSource
bnProducts.BindingSource = bsProducts; // BindingNavigator
dataGridView1.DataSource = bsProducts; //
}

private void bindingNavigatorDeleteItem_Click(object sender, EventArgs e)
{

Product product = (Product)bsProducts.Current;

// Putting a breakpoint here, shows the identity property is not the same
// as row selected in datagridview.

main.DeleteProduct(product);

}

Answer

I understood now that the row is deleted before the CellClick event fires. So I make it work as intended by instead putting the code in the _MouseDown event of the delete button. Not sure if this is the most proper solution though..

    private void btnDeleteProducts_MouseDown(object sender, MouseEventArgs e)
    {
        Product product = (Product)bsProducts.Current;
        if (product != null)
        {
           main.DeleteProduct(product);
        }                 
    }