简体   繁体   English

C#中的多个组合框

[英]multiple combo box in c#

I am new to c#. 我是C#的新手。 I am trying to create multiple combo boxes based on result from query. 我正在尝试根据查询结果创建多个组合框。 If the query results 5 items I need to make 5 combo boxes. 如果查询结果为5个项目,我需要制作5个组合框。 But I do not know how to add event handler( on selection changed event). 但是我不知道如何添加事件处理程序(选择更改的事件)。 I am using an array of combo boxes and number of boxes may vary. 我使用的是组合框数组,框数可能会有所不同。 How do I come to know which comboBox of this array was changed and handle the event for same 我如何知道此数组的哪个comboBox已更改并为之处理事件

Assuming this is WinForms... 假设这是WinForms ...

As you are creating the controls, assign a generic event handler: 在创建控件时,分配一个通用事件处理程序:

foreach (DataRow row in ADataTable)
{
    ComboBox box = new ComboBox();
    box.OnSelectionChanged += comboBox_OnSelectionChanged;
}

protected void comboBox_OnSelectionChanged(Object sender, EventArgs e)
{
    if (sender is ComboBox)
    {
        ComboBox box = (ComboBox)sender;
        //do what you like with it
    }
}

In order to operate on the ComboBox in question, you need know nothing about the array. 为了在有问题的ComboBox上进行操作,您无需了解任何有关阵列的知识。 In fact, you probably don't need the array at all unless there is more to the story. 实际上,除非故事有更多内容,否则您可能根本不需要阵列。

you could either create a child class of the combo box in which case you can override the event, or you can get the name of your combobox and do something like so 您可以创建组合框的子类,在这种情况下,您可以覆盖事件,也可以获取组合框的名称并执行类似的操作

comboboxName.OnSelected += (obj, args) => MethodToCall();

I dont think that is the exact name of the event but that should get you started. 我不认为这是事件的确切名称,但是应该可以帮助您开始。 There are multiple variations of handling the event such as 处理事件有多种变体,例如

comboboxName.OnSelected += MethodToCall;
void MethodToCall(Object sender, EventArgs e){}

or 要么

comboboxName.OnSelected += () => delegate{/*put some code here*/};

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

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