简体   繁体   中英

C# DataGridView throws exception when removing object from BindingList

Everything was working fine, until I ran this code:

TicketLine tl = (TicketLine)dgTicketLines.SelectedRows[0].DataBoundItem;
tl.Items--;
if (tl.Items < 1)
    CurrentTicket.TicketLines.Remove(tl);

CurrentTicket.TicketLines is a BindingList<TicketLine>

I get several IndexOutOfRange exceptions in the DataGridView when running the above code.

采取ObservableCollection<TicketLine>而不是BindingList,它应该可以工作。

You need to suppress the ListChanged event by setting BindingList<TicketLine>.RaiseListChangedEvents = false; and then call BindingList<TicketLine>.ResetBindings(); when you want any changes to get propagated over to the DataGridView. There are other ways of doing this of course, but this has always worked fine for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM