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.