将List传递给函数(object sender,EventArgs e)



我有一个函数RadioButtonList_SelectedIndexChanged,在这个函数中我创建了一个列表,我想将列表传递给另一个函数:DropDownList_SelectedIndexChanged(object sender, EventArgs e)

我怎样才能做到这一点?

您有两种可能的解决方案:

将List对象作为事件发送者发送(不推荐)

您可以利用事件处理程序采用object参数的优势,该参数是事件的发送方。您可以使用此参数在您的列表中传递:

DropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
      // You'll have to downcast the object
      List<string> myList = sender as List<string>;
}

您可以从单选按钮事件处理程序中这样调用它:

RadioButtonList_SelectedIndexChanged(obejct sender, EventArgs e)
{
    // ...
    DropDownList_SelectedIndexChanged(yourCreatedList, null);
}

不建议这样做,因为这个参数应该包含sender对象,在您的情况下,它是您的单选按钮,而不是列表。

创建您自己的EventArgs(推荐)

您可以创建自己的EventArgs:实现

public class DropDownListEventArgs : EventArgs
{
     public List<string> List;
}

然后,您应该修改您的事件处理程序签名:

DropDownList_SelectedIndexChanged(object sender, DropDownListEventArgs e)
{
      List<string> myList = e.List;
}

您可以从单选按钮事件处理程序中这样调用它:

RadioButtonList_SelectedIndexChanged(obejct sender, EventArgs e)
{
    // ...
    DropDownList_SelectedIndexChanged(yourRadioButton, new DropDownListEventArgs()
    {
         List = yourCreatedList
    });
}

p.S.:我假设您的列表是List<string>类型,但它可以是任何类型。

在代码后面创建私有List变量,从数据库中检索更改为该变量的radiobutton上的数据,然后只在dropdownlistrongelectedindexchanged函数中使用该变量。我认为这比使用(object sender,EventArgs e)进行操作要好;

private List list1;

最新更新