tags:

views:

95

answers:

4

Hi, Could some one please show me how I can rewrite the below method in a better and more elegant way?

// in class------------------

    public static void RefreshAllDropdownlists(DropDownList ddlRemoveUsersFromRole, DropDownList ddlAddUsersToRole, DropDownList ddlAddAllUsersToRole, DropDownList ddlRemoveAllUsersFromRole, DropDownList ddlDeleteAllUsersFromRole)
    {
        ddlRemoveUsersFromRole.ClearSelection();
        ddlAddUsersToRole.ClearSelection();
        ddlAddAllUsersToRole.ClearSelection();
        ddlRemoveAllUsersFromRole.ClearSelection();
        ddlDeleteAllUsersFromRole.ClearSelection();
    }

// in codebehind------------------

UserGvUtil.RefreshAllDropdownlists(ddlRemoveUsersFromRole, ddlAddUsersToRole, ddlAddAllUsersToRole, ddlRemoveAllUsersFromRole, ddlDeleteAllUsersFromRole);

Thank you!

+1  A: 

Something like

public static void RefreshAllDropdownlists(params DropDownList[] dropDownLists)
{
    if (dropDownLists != null)
        foreach (var ddl in dropDownLists)
            ddl.ClearSelection();
}

?

herzmeister der welten
+1  A: 

You could pass a list of DropDownList objects to the function, then you could do:

public static void RefreshAllDropdownlists(List<DropDownList> lists)
{
   foreach(DropDownList dropDown in lists)
   {
     dropDown.ClearSelection();
   }
}
Russell
+7  A: 

Use the params parameter modifier to pass an array of DropDownLists :

public static void RefreshAllDropdownlists(params DropDownList[] dropDownLists)
{
    foreach (DropDownList ddl in dropDownLists)
    {
        ddl.ClearSelection();
    }
}

Usage is is the same as with your current method

Thomas Levesque
Awesome, thank you! This is exactly what I was aiming for but could not figure out the syntax.
John Walsh
+2  A: 
var listsToRefresh = new List<DropDownList>
                {
                    ddlRemoveUsersFromRole,
                    ddlAddUsersToRole,
                    ddlAddAllUsersToRole,
                    ddlRemoveAllUsersFromRole,
                    ddlDeleteAllUsersFromRole
                };
listsToRefresh.ForEach(l=>l.ClearSelection());

There are many ways to do this, I would prefer this one. If all you are doing is performing ClearSelection() on each one, then there is no need to create a method for that one line of code. However, if you want to do some more work on each DropDownlist, then I think the use of an extension method would keep it elegant.

 public static class DropDownListExtensions
    {
        public static void Reset(this DropDownList dropDownList)
        {
            dropDownList.ClearSelection();
            //... do more stuff

        }
    }

listsToRefresh.ForEach(l=>l.Reset());
Tion