正确的列表框事件来处理列表框中的更改? (C#)
我有一个列表框,其中包含一些项目。有两个按钮用于添加和删除列表框项目。关闭表单时,如果对列表框进行任何更改,我需要一个确认消息框。所以基本上,表单需要知道列表框中的项目是否发生更改。哪个是设置更改标志的正确列表框事件?
注意:当然,我可以通过单击“添加”按钮和“删除”按钮来处理此问题,但这不是正确的方法。不是这样吗?所以没有肮脏的伎俩,但正确的方法?
I have a listbox with some items in it. There are two buttons to add and remove listbox items. When closing the form, I need a confirmation message box if any changes are made to the listbox. So basically, form needs to know if items in listbox are changed. Which would be the right listbox event to set a changed flag?
Note: Of course I can handle this from Add button and Remove button clicks, but that's not the right way to do it. Ain't so? So no dirty tricks, but the right approach??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果直接使用列表框,不,没有事件会告诉您列表已更改。
最好让 ListBox 使用像 BindingList 这样支持 ListChanged 事件的数据源。
If just using a ListBox straight up, no, there isn't an event that will tell you the list has changed.
It's better to have the ListBox use a DataSource like BindingList which supports a ListChanged event.
我认为您应该从实际执行项目添加和删除所调用的方法中设置“脏”标志。这样,如果您决定添加其他方法来与列表框交互(上下文菜单、键盘快捷键等),您的逻辑就全部集中在一个地方并可以重复使用。
因此,您的 add 方法看起来像这样:
不过,这是一个有点幼稚的方法,因为现在添加一个项目然后删除它会导致提示,即使列表实际上并未从其原始状态更改。如果列表的大小不太大,另一种选择是在首次加载支持数据时制作备份数据的副本,然后将最终数据与该副本进行比较。如果没有差异,则无需提示。
I think you should be setting the "dirty" flag from the methods that are called to actually perform the item addition and removal. That way, if you decide to add additional methods for interacting with the list box (a context menu, keyboard shortcut, etc.) your logic is all in one place and ready to be re-used.
So your add method would look something like this:
That's a somewhat naive method, though, since now adding an item and then removing it results in a prompt, even though the list hasn't actually changed from its original state. If the size of your list isn't too big, another option would be to make a copy of the backing data when it is first loaded, and then to compare the final data against that copy. If there's no differences, you don't have to prompt.