简体   繁体   English

在代码中触发 OnSelectedIndexChanged 事件

[英]Firing a OnSelectedIndexChanged event within code

As well as this event firing from the drop down, I would also like to be able to fire it from my code.除了从下拉菜单中触发此事件外,我还希望能够从我的代码中触发它。 Is this possible and if so how?这可能吗?如果可以,怎么办?

Thanks谢谢

Stu斯图

The best way to do this is to wrap the code from the event into a method, and call it from both places.最好的方法是将事件中的代码包装到一个方法中,并从两个地方调用它。

BUT if you did want to call the event directly (which I don't recommend), you can do it like this:但是,如果您确实想直接调用事件(我不推荐),您可以这样做:

MyComboBox_SelectedIndexChanged(null, null);

(Unless you use either the sender or EventArgs within the method, then you will need to supply these too) (除非您在方法中使用senderEventArgs ,否则您也需要提供这些)

If you want to fire the SelectedIndexChanged event from code you could either call the event handler like CmbBox_SelectedIndexChanged(null, null);如果您想从代码中触发SelectedIndexChanged事件,您可以调用事件处理程序,例如CmbBox_SelectedIndexChanged(null, null); or do或者做

   if(CmbBox.SelectedIndex <> index)//let index is a int variable
      CmbBox.SelectedIndex = index;       
   else
   {
      CmbBox.SelectedIndex = -1;
      CmbBox.SelectedIndex = index;
   }

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

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