Setting up a combobox to execute selections

  • Thread starter Thread starter Robert in SF
  • Start date Start date
R

Robert in SF

Guest
Although this discussion involves a combobox, it's not really about Winforms but about C# itself. Consider, then, a combobox, and each of its entries corresponds to a method you wish to invoke. A common way to do this is:

private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
var cmb = sender as ComboBox;
switch (cmb.SelectedIndex)
{
case 0:
FunctionA();
break;
case 1:
FunctionB();
break;
case 2:
FunctionC();
break;
default:
break;
}
}


This is a very simple solution, but some people don't like it for various reasons. Regardless of the pros and cons, there is a way of achieving the same result without any switch statement.

At the class level, declare,

private List<string> userOptions = new List<string>();
private List<Func<bool>> methods = new List<Func<bool>>();


Then, after InitializeComponent(),

InitializeComponent();

methods.Add(FunctionA);
methods.Add(FunctionB);
methods.Add(FunctionC);

userOptions.Add("Feature A name");
userOptions.Add("Feature B name");
userOptions.Add("Feature C name");

ComboBox1.DataSource = new BindingSource(userOptions, null);
ComboBox1.SelectedIndex = -1;


Now the ComboBox will display the items from the userOptions list. When the user selects an entry in the ComboBox, the SelectedIndexChanged event fires. The SelectedIndex property is then used to select the method to invoke.

private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
var cmb = sender as ComboBox;
if ((cmb.SelectedIndex == -1) is false)
{
methods[cmb.SelectedIndex].Invoke();
}
}


What do you think? Which of the two methods is the better practice? Can you simplify it more? I couldn't find a way to use just one collection.

Continue reading...
 
Back
Top