C# 即使新旧索引相同,是否也可以触发 ComboBox SelectedIndex Changed Event?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19829381/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to fire ComboBox SelectedIndex Changed Event even when old and new index are same?
提问by SamuraiHyman
I have a scenario is which I need to fire the SelectedIndexChanged
event of a winform's combox even when the old and new index is same.. I can not use SelectionChangeCommited
because the values are being set programmatically .. and it wont get fired. Is it by any chance to force 'SelectedIndexChanged' to fire even when old and same index are same?
我有一个场景,SelectedIndexChanged
即使旧索引和新索引相同,我也需要触发winform 组合框的事件SelectionChangeCommited
。即使旧索引和相同索引相同,是否也有机会强制“SelectedIndexChanged”触发?
采纳答案by Sinatr
Nothing prevents you from calling event handler directly:
没有什么可以阻止您直接调用事件处理程序:
comboBox1_SelectedIndexChanged(comboBox1, new EventArgs()); // or (null, null)
But solution of atomaras
is a better (nicer) way to do it.
但是解决方案atomaras
是一种更好(更好)的方法。
I myself dislike to use standard components in more-less serious software. Instead I subclass all standard components from very beginning and adding functionality to them as soon as I need it without needs to change anything in the existing forms.
我自己不喜欢在较不严肃的软件中使用标准组件。相反,我从一开始就对所有标准组件进行子类化,并在需要时立即向它们添加功能,而无需更改现有表单中的任何内容。
In this case I'd add a public event riser OnSelectedIndexChanged
to execute event (to run code inside event handler programmatically).
在这种情况下,我会添加一个公共事件提升器OnSelectedIndexChanged
来执行事件(以编程方式在事件处理程序中运行代码)。
回答by atomaras
It seems wierd that you want the event to refire for the same item. It's probably because you just want to reexecute the event handler logic. Why dont you extract the SelectionChanged logic into a new method and call that one programmatically?
您希望事件为同一项目重新触发似乎很奇怪。这可能是因为您只想重新执行事件处理程序逻辑。为什么不将 SelectionChanged 逻辑提取到一个新方法中并以编程方式调用该方法?
回答by Rahul Sahu
combobox.selectedIndex = value;
combobox.selectedevent(null,null);