Dynamically generated dynamic RadioButtonsList

I'm working on an interesting survey form and I'm trying to break the boredom by making the process more complicated. I have a radobuttonlists group that I want to dynamically create from a name string and a value string. The values ​​are not a problem. This has created all the radio amateurs that I cannot understand.

For example, I could keep doing this:

    string[] level = {"Expert", "Proficient", "Limited Experience", "No Experience"};

    this.rblCSharp.Items.Clear();
    for (int i = 0; i < level.GetLength(0); i++) {
        this.rblCSharp.Items.Add(level[i]);
    }
    this.rblCSharp.RepeatDirection = RepeatDirection.Horizontal;


    this.rblVbNet.Items.Clear();
    for (int i = 0; i < level.GetLength(0); i++)
    {
        this.rblVbNet.Items.Add(level[i]);
    }
    this.rblVbNet.RepeatDirection = RepeatDirection.Horizontal;

      

... but I do not want. I want to do something more:

    string[] level = {"Expert", "Proficient", "Limited Experience", "No Experience"};

    string[] language = { "CSharp", "VbNet", "VbClassic", "Crystal", "Ssrs", "Sql2005", "UiWeb" };

    for (int j = 0; j < language.GetLength(0); j++) {
        this.rbl[j].Items.Clear();
        for (int i = 0; i < level.GetLength(0); i++) {
            this.rbl[j].Items.Add(level[i]);
        }
        this.rbl[j].RepeatDirection = RepeatDirection.Horizontal;
    }

      

+2


source to share


1 answer


You need a way to reference the language-specific RadioButtonList controls. You have a string array, so one way would be to use FindControl, but that would not be my preference.

Another way:

var languageControls = new List<RadioButtonList> { rblCSharp, rblVbNet, rblVbClassic, rblCrystal, rblSsrs, rblSql2005, rblUiWeb };

foreach(var rbl in languageControls)
{
    rbl.Items.Clear();
    // this could be a foreach instead, but I kept your original code
    for (int i = 0; i < level.GetLength(0); i++)
    {
        rbl.Items.Add(level[i]);
    }
    rbl.RepeatDirection = RepeatDirection.Horizontal;
}

      




FindControl approach (this only makes sense if you dynamically created and added the RadioButtonList controls and were not available in markup and through IntelliSense)

string[] level = {"Expert", "Proficient", "Limited Experience", "No Experience"};
string[] language = { "CSharp", "VbNet", "VbClassic", "Crystal", "Ssrs", "Sql2005", "UiWeb" };

foreach (string lang in language)
{
    RadioButtonList rbl = (RadioButtonList)FindControl("rbl" + lang);
    if (rbl == null)
        continue;  // keep going through the rest, or throw exception

    rbl.Items.Clear();
    // this could be a foreach instead, but I kept your original code
    for (int i = 0; i < level.GetLength(0); i++)
    {
        rbl.Items.Add(level[i]);
    }
    rbl.RepeatDirection = RepeatDirection.Horizontal;
}

      

0


source







All Articles