Using a windows forms ListBox, how can I bind both double-click and return key to a single action. The way I have it I just copied the same action into both listBox1_MouseDoubleClick and listBox1_KeyUp.
public partial class MyForm : Form
{
public MyForm()
{
InitializeComponent();
}
private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
{
this.textBox1.Text = this.listBox1.SelectedItem.ToString(); // Repeated
}
private void listBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Return)
{
this.textBox1.Text = this.listBox1.SelectedItem.ToString(); // Repeated
}
}
}
Not really a big deal for just two events but is there a way to bind both of these listeners to the single action?
Since signatures of the two events’ delegates are different you can’t really combine event handlers, especially if you need the keyboard handler to have some additional logic, like checking which key was pressed.
But, what you can do is put the assignment into its own method and then call it from both event handlers. That way you will not be violating DRY principle and if you would ever need to extend the action you’d only need to do it in one place as well as if you would want to use this same action for some other event you’ll be able to do it just by calling the method.