user1965804 user1965804 - 1 year ago 91
C# Question

How to dynamically assign method combobox

I have several methods that I want to execute according to the selected value of a combobox.
I'm currently using the following code:

switch (comboBox1.SelectedIndex)
case 1:
// call method1
case 2:
// call method2

Is there a good way to get the same thing like if
combobox.selectedIndex == 1
then auto call to method 1?

Answer Source

The simplest way is through the use of delegates:

private readonly Dictionary<int, Action> actions = new Dictionary<int, Action>
    { 1, Method1 },
    { 2, Method2 },
    { 3, Method3 },

Which allows you to do something like this:


You could also use reflection, of course, but keeping things statically linked has plenty of benefits :)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download