0

I have a block of common drop-boxes that I would like to iterate through rather than go through all of them every time, even when only the first few are needed. They all have the exact same name, except for the number referring to their specific place in the hierarchy.

Essentially, there is a MaxSpellLevel value that determines up to what spell level this particular class or character can use. If the Max Spell Level is only 2, there's no reason to go all the way up to 9, since everything after 2 is unneeded anyway.

The code I have thus far is this:

if(cbox_Magical.Text != "Non-Magical") {
    // Save Spell Information Here
    int MaxSpellLevel = int.Parse(cbox_MaxSpell.Text);
    for(int i = 0; i <= MaxSpellLevel; i++) {
        string KnownString, PerDayString;
        KnownString = "cbox_Known" + Convert.ToString(i);
        PerDayString = "cbox_PerDay" + Convert.ToString(i);

        Type Known = Type.GetType(KnownString);
        Type PerDay = Type.GetType(PerDayString);

        XElement SpellKnown = new XElement("SpellsKnown",
            new XAttribute("level", Convert.ToString(i)),
            Known.Text);

        XElement SpellUse = new XElement("SpellUse",
            new XAttribute("level", Convert.ToString(i)),
            PerDay.Text);

        c.Add(SpellKnown);
        c.Add(SpellUse);
    }
}

I have a series of drop-down boxes that are all labeled 'cbox_Known0', 'cbox_Known1', etc. Is there a way to do what I'm attempting below? I have looked into reflection, but unfortunately do not understand it or it isn't for what I'm attempting.

MCourneya
  • 17
  • 4
  • For winforms, you don't need reflection. You're able to grab the control based on its Id (in your example, `KnownString` and `PerDayString` - you won't need `Type.GetType()` at all). See linked duplicate – Rob Jul 04 '17 at 23:59
  • Store them in an array, and in your for-loop only check the necessary controls. – Ian Jul 05 '17 at 00:00
  • @Rob is correct, you can search by name. However, it would actually be better if you just stored the references to the control objects in an array (or a `List`, which gives you a convenient way to vary the length of the collection). See the other marked duplicate. – Peter Duniho Jul 05 '17 at 00:01
  • Awesome, thanks for the help, everyone! – MCourneya Jul 05 '17 at 00:17

0 Answers0