Error when deleting second item from List

2

I'm using the following code to exclude items:

if (e.KeyCode == Keys.Delete)
{
    var remover = listaPedido.SingleOrDefault(r => r.ItemOffline == int.Parse(gridPedido.CurrentRow.Cells[3].Value.ToString()));
    if (remover != null)
    {
        listaPedido.Remove(remover);
        gridPedido.DataSource = listaPedido;
    }   
}

The first time I delete an item, it works correctly. The second time gives OutOfIndex error (even though I have items in my list):

Look at the screen behind the error, I still have 3 records in the dataGrid.

What can it be?

    
asked by anonymous 08.01.2017 / 21:23

2 answers

3

You have not posted the whole code, only the excerpt, but I will assume the following (based on the error that occurs):

  • Your grid is initialized with the variable listaPedido , which in turn must be a List<QualquerCoisa> ;
  • At some point you start the list with gridPedido.DataSource = listaPedido ;
  • Note that when you delete an item from listaPedido , you re-match that listaPedido to your gridPedido.DataSource , which in practice has no effect. Your grid already has listaPedido as its DataSource ;
  • The type List<T> does not have change notification events built in - in practice, your grid is not aware of the change and relies on rendering the previous state (when it still had 3 items), generating the error. >

Solution

Simply encapsulate your data source into a BindingList<QualquerCoisa> (replace QualquerCoisa with the actual name of your class) . So:

BindingList<QualquerCoisa> _bsListaPedido;  // Variável Global da Classe

void CarregaGrid() 
{
    _bsListaPedido = new BindingList<QualquerCoisa>(listaPedido);
    gridPedido.DataSource = _bsListaPedido;
}

When removing the item from the list, remove it from BindingList :

_bsListaPedido.Remove(remover);

This will notify the Grid of the change properly and everything should be fine.

    
09.01.2017 / 00:07
1

I was able to solve this:

if (e.KeyCode == Keys.Delete)
{
    var remover = listaPedido.SingleOrDefault(r => r.ItemOffline == int.Parse(gridPedido.CurrentRow.Cells[3].Value.ToString()));
    if (remover != null)
    {
        listaPedido.Remove(remover);
        gridPedido.DataSource = null;
        gridPedido.DataSource = listaPedido;
    }   
}

adding the line gridPedido.DataSource = null; caused dataGridView to "zero" and updated it again with the current list.

    
08.01.2017 / 23:55