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!
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
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());
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With