2

I have an abstract class

public abstract class PairingMethod : IPairingMethod
 {
    virtual string Name { get; } = "Default Pairing";

    protected ICollection<IPlayer> PlayersToPair { get; set; }


    protected PairingMethod(ICollection<IPlayer> players )
    {
        PlayersToPair = players;
    }

    public virtual void GeneratePairingsForRound(IRound round)
    {
        throw new System.NotImplementedException();
    }

}

Now I've tried to create a combo box based on all types that derive from that base class above. I created the combo box, and it uses class names as items but then when the combo box change event is triggered I need to know which derived class was selected. Then i can create an instance of that class, for generating pairings.

I tried implementing my own combo box with PairingMethods as the items but can't get it to work.

Any ideas/ suggestions?

C

Jack
  • 131
  • 1
  • 9
  • 2
    1. Format your code properly please, the indentation is all over the place here. 2. Show your combo box code, that's the important bit here. – DavidG Feb 09 '17 at 16:03
  • `"it uses class names as items [...] I need to know which derived class was selected"` - Wouldn't that just be the current selected value of the combo box then? It's not really clear what the problem is here. – David Feb 09 '17 at 16:07
  • Sorry David, I can get the index from a selected item. But what would be a clean way of converting a selected index into the derived class? – Jack Feb 09 '17 at 16:08
  • @user7541312 you would use the class name and not the index. Then that would be done like here: [Create an instance of a class from a string](http://stackoverflow.com/questions/223952/create-an-instance-of-a-class-from-a-string) – Mong Zhu Feb 09 '17 at 16:11
  • ahh thankyou Mong Zhu – Jack Feb 09 '17 at 16:12

1 Answers1

1

Thanks to Mong Zhus advice i did the following

public class PairingComboBox : ComboBox
{
    private List<Type> _availableMethod = DerivedTypes.FindAllDerivedTypes<PairingMethod>();

    public PairingComboBox()
    {
        DataSource = DerivedTypes.FindAllDerivedTypes<PairingMethod>();
        DisplayMember = "Name";
    }
}

public static IPairingMethod CreateInstanceBinder
               (string pairingMethodName, ICollection<IPlayer> players)
{
         var t = Type.GetType(pairingMethodName + ",Pairings");
        return (PairingMethod)Activator.CreateInstance(t, players);
 }

I call the CreatenIstanceBuilder when the combo box changes. Passing in the players from the league.

Jack
  • 131
  • 1
  • 9