2

我正在寡妇 c#.net 中开发项目。在表单中,我有超过 8 个组合框控件。当 combobox1 选择更改如下时,我会将数据加载到 combobox2。

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
     comboBox2.DataSource = DataTable;
     comboBox2.DisplayMember="Name";
     comboBox2.ValueMember = "ID";
}

当我选择下面的 combobox2 时,将加载 Combobox3。

 private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
 {
     comboBox3.DataSource = DataTable;
     comboBox3.DisplayMember = "Age";
     comboBox3.ValueMember = "AgeCode";
 }

就像我将数据加载到组合框的其余部分一样。
这里的问题是会发生错误,如果我没有检查comboBox1_SelectedIndexChanged方法是否加载了comboBox2。

我知道我们可以通过使用布尔变量来检查这一点,但可怕的是我们需要为所有方法保持其“真/假”状态。

所以我想以简单的方式解决这个问题是,我将使用Add(combobox, Methodname)方法和方法从组合框事件Remove(combobox, method)中添加和删除comboBox_SelectedIndexChanged函数。SelectedIndexChanged

但我无法将该方法作为参数传递。谁能告诉我如何将方法作为参数传递给我的要求。

4

3 回答 3

3

如果您的意思是和/或然后解决方案是,则通过method参数Add和方法RemovecomboBox1_SelectedIndexChangedcomboBox2_SelectedIndexChanged

private void Add(ListControl dropDownList, EventHandler handlerMethodName)
{
   dropDownList.OnSelectedIndexChanged += handlerMethodName;
   //some logic here
}

private void Remove(ListControl dropDownList, EventHandler handlerMethodName)
{
   dropDownList.OnSelectedIndexChanged -= handlerMethodName;
   //some logic here
}

请注意:它DropDownListASP.NETComboBox用于WinForms应用程序。

有关更多信息,请参阅:MSDN - DropDownListMSDN - ListControl.SelectedIndexChanged 事件

于 2013-03-18T11:26:49.027 回答
1

我不确定您要做什么。但为什么不是 ComboBox 和方法的字典呢?

像这样:

var dict = Dictionary<ComboBox, Action<object, EventArgs>>();

private void Add(ComboBox c, Action<object, EventArgs>e) {
   dict[c] = e;
}

private void Remove(ComboBox c, Action<object, EventArgs> e) {
   dict.Remove(c);
}

并致电::

private void CallHandler(ComboBox c, EventArgs e)
{
   dict[c](c, e);
}

或者

private void AddHandler(ComboBox c, Action<object, EventArgs> e)
{
   c.SelectedIndexChanged += e;
}

private void RemoveHandler(ComboBox c, Action<object, EventArgs> e)
{
   c.SelectedIndexChanged -= e;
}
于 2013-03-18T11:14:27.823 回答
1

我也不是 100% 确定您正在寻找那种解决方案,但我对您的需求的理解是以下方法:

public void Add(DropDownList combo, EventHandler method)
{
    combo.SelectedIndexChanged += method;
}

public void Remove(DropDownList combo, EventHandler method)
{
    combo.SelectedIndexChanged -= method;
}

现在您可以定义自己的方法,该方法应该与EventHandler委托具有相同的签名:

public void MyMethod1(object sender, EventArgs e)
{}

您可以通过调用上述定义的方法来注册和注销您的方法:

DropDownList lst = new DropDownList();
Add(lst, MyMethod1);
Remove(lst, MyMethod1);

但请注意,这可能不是您问题的最佳解决方案。

于 2013-03-18T11:27:09.560 回答