简体   繁体   English

从BindingList中删除对象时,C#DataGridView引发异常

[英]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> CurrentTicket.TicketLines是BindingList<TicketLine>

I get several IndexOutOfRange exceptions in the DataGridView when running the above code. 运行上面的代码时,我在DataGridView中收到几个IndexOutOfRange异常。

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

You need to suppress the ListChanged event by setting BindingList<TicketLine>.RaiseListChangedEvents = false; 您需要通过设置BindingList<TicketLine>.RaiseListChangedEvents = false;来抑制ListChanged事件BindingList<TicketLine>.RaiseListChangedEvents = false; and then call BindingList<TicketLine>.ResetBindings(); 然后调用BindingList<TicketLine>.ResetBindings(); when you want any changes to get propagated over to the DataGridView. 当您希望将任何更改传播到DataGridView时。 There are other ways of doing this of course, but this has always worked fine for me. 当然,还有其他方法可以执行此操作,但这对我来说一直很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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