Question

i have a web form with a 5 of asp.net dropdownlist on. I would like to have a method in the code behind that allows me to pass in the name of the dropdownlist and disables it. I have the following code which works but i think it could be written cleaner allowing me to disable more than one dropdownlist when calling the method once, as opposed to currently where if i want to disable two or three i must call the method three times each time passing the different names of the dropdownlist. i hope the code below makes it a bit clearer:

public partial class _Default : Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        disableDropDown(DropDownList1);
    }


    protected DropDownList disableDropDown(DropDownList a)
    {
        if (a != null)
        {
            a.Enabled = false;
            return a;
        }
        else
        {
            return null;
        }

    }


} 

Would it be better to have something like disableDropDown(DropDownList1, DropDownList2); for example if i wanted to disable two boxes, instead of having to call the same method twice with different dropdownlists? If so, how would my actual "disableDropDown" function be modified to allow more than one dropdownlist?

Many thanks

Was it helpful?

Solution

One way, you could use a params array:

public static void EnableControls(bool enable, params WebControl[] controls)
{
    foreach (WebControl c in controls)
    {
        if (c != null) c.Enabled = enable;
    }
}

Note that

  • I return void(nothing) since you just set a property of already available controls. Returning them would be pointless
  • I have added a parameter enable which allows to enable or disable the controls
  • I have changed it to acceppt WebControls since that's the class with the Enabled property, on this way you can use it for other controls like TextBox or Label as well, so your method is more useful
  • public static makes it also more usable, you don't need to access the instance of the surrounding Page-class anyway.

You can call it with single DropDownLists:

EnableControls(false, dropdown1, dropdown2, dropdown3);

or with an array (pseudo code):

var manyDropDowns = new DropDownList[]{ dropdown1, ..., dropDown999999 };
EnableControls(false, manyDropDowns);

OTHER TIPS

You could use params. (Also, you don't need to return anything from here.)

protected void DisableDropDown(params DropDownList[] ddls)
{
    foreach(var ddl in ddls)
    {
        ddl.Enabled = false;
    }
}

And use it like so:

DisableDropDown(DropDownList1, DropDownList2, DropDownList3);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top