如何在C#中编写多个组合框的单个事件 [英] How To Write Single Event For Multiple ComboBoxes In C#

查看:77
本文介绍了如何在C#中编写多个组合框的单个事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨朋友们......

我们可以为不同的组合框执行相同的事件...例如我有5个组合框...所有5个组合框都执行相同的事件代码...现在我们可以为所有组合框编写单个事件......在C#中,Winforms ...



请帮助我

hi Friends ...
Can We Perform Same Event For Different ComboBoxes...For Example I Have 5 ComboBoxes...All The 5 ComboBoxes Are Performing Same Code Of Event...Now Can We Write Single Event For All The ComboBoxes...in C#,Winforms...

Pls help Me

推荐答案

您所说的不是同一个事件,而是关于相同的事件句柄。你总能做到。当然,在事件处理程序中,您可能需要获取特定于控件的每个实例的信息,在该控件中已将事件处理程序添加到某个事件实例的调用列表中。你总是可以通过传递给处理程序的参数来完成它。



以下是它的外观:



You are talking not about the same event, but about the same event handle. You always can do it. Naturally, in your event handler, you might need to get information specific to each instance of the control in which you have added an event handler to the invocation list of some event instance. You can always do it through the arguments passed to the handler.

Here is how it might look:

// suppose you already have some combo boxes, say, an array of them:
ComboBox[] comboBoxes = // ...

//...

foreach (ComboBox comboBox in comboBoxes)
   comboBox.SelectedIndexChanged += (sender, eventArgs) => { // let's take this event; it is often used
       ComboBox instance = (ComboBox)sender; // you can bravely do this case and be sure it's a ComboBox
       int selectedIndex = instance.SelectedIndex;
       // in other cases, you can also use eventArgs, for example, mouse coordinates for mouse events
       SomeActionOnComboBoxSelectedIndexChanged(instance, selectedIndex);  
   };

//...

// note that the parameters are strongly typed:
void SomeActionOnComboBoxSelectedIndexChanged(ComboBox sender, int newIndex) {
    // and not, this code can be used for all combo boxes
}





这样的事情。



祝你好运,

-SA

是...假设,我们为一个ComboBox编写了事件..现在您需要做的就是为其他组合框调用此事件。就像在您的VS IDE中一样,转到comboBox的事件选项卡并选择您的其他ComboBoxes的书面活动...

或其他代码,



Yes... Suppose, we have written event for one ComboBox.. Now all you need to do is call this event for other comboboxes.. Like in your VS IDE go to comboBox''s event tab and select your written event for other ComboBoxes...
or else by code,

private void ComboBox1_SelectedIndexChange(object sender, EventArgs e)
{
     // code...
}

private void ComboBox2_SelectedIndexChange(object sender, EventArgs e)
{
     ComboBox1_SelectedIndexChange(sender, e);
}

private void ComboBox3_SelectedIndexChange(object sender, EventArgs e)
{
     ComboBox1_SelectedIndexChange(sender, e);
}


这篇关于如何在C#中编写多个组合框的单个事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆