Search code examples
c#asp.netdrop-down-menuformview

How to make several DropDownlists read from the same datasource in a non-Redundant way?


I have about 4 fields built inside a form view but each have to appear to a maximum of 10 if the user wishes to add more info (Note: this is required)

so its like :NameTextBox1 till NameTextBox10 and TestTextBox1 till TestTexBox10

If the user clicks the "add field" button the extra textboxes appear.

Now for the Question: One of the fields is a dropdownlist henceforth I have 10 dropdownlists that all have the same info they all read from the same function. Is there a more efficient way to go about doing the below procedure than writing the same thing 10 times?

 DropDownList DropDownList1 = (DropDownList)EntryFormView.FindControl("DropDownList1");
  DropDownList1.DataSource = GeographicManager.ReadLocations();
  DropDownList1.DataBind();

Solution

  • Wrap it into another function that takes IDs:

    private void initDropDown(string dropDownID)
    {
        DropDownList DropDownList1 = (DropDownList)EntryFormView.FindControl(dropDownID);
        DropDownList1.DataSource = GeographicManager.ReadLocations();
        DropDownList1.DataBind();
    }
    
    initDropDown("DropDownList1");
    initDropDown("DropDownList2");
    

    If you need to init them all at once, you can use a loop to do so:

    for (int i=1; i<=10; i++)
    {
        initDropDown("DropDownList" + i);
    }
    

    Or you can put their IDs in an array and iterate over that. Also useful if your IDs do not follow simple pattern of "DropDownListX":

    string[] dropDownIDs = ["DropDownList1", "DropDownListTwo", "TheDropDownList"];
    
    foreach (String ID in dropDownIDs)
    {
        initDropDown(ID);
    }