简体   繁体   中英

Pass List to function with (object sender, EventArgs e)

I have a function RadioButtonList_SelectedIndexChanged and in this function i created a list and i want to pass the List to a nother function: DropDownList_SelectedIndexChanged(object sender, EventArgs e)

How can I achieve that?

Create private List variable in the code behind, retrieve your data from database on radiobuttonchanged to that variable, and then just use that variable inside dropdownlist_selectedindexchanged function. I think it is better way than manipulating with (object sender, EventArgs e);

private List list1;

You have two possible solutions:

Send the List object as the event sender (Not recommended)

You may take advantage that event handlers take an object argument, which is the sender of the event. You may use this argument to pass in your list:

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

You would call it like this from your radio button event handler:

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

This is not recommended, because this argument is supposed to hold the sender object, which in your case, is your radio button, not a list.

Create your own EventArgs (Recommended)

You can create your own implementation of EventArgs :

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

You should then modify your event handler signature:

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

You would call it like this from your radio button event handler:

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

PS : I'm assuming your list is of type List<string> , but it can be of any type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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