In a Windows Forms app, there are some things I want various controls of the same type on different forms to always do upon certain events. For example, I want a single click on a DataGridViewCell that is a TextBox-type and is not read only to automatically enter edit mode. The simple event handler code, in this case on a form with a DataGridView called dgvParms, is:
private void dgvParms_CellClick(object sender, DataGridViewCellEventArgs e) {
DataGridViewCell c = dgvParms[e.ColumnIndex, e.RowIndex];
if (!c.ReadOnly && c is DataGridViewTextBoxCell) {
dgvParms.CurrentCell = c;
dgvParms.BeginEdit(true);
}
}
I could easily move this method to a static class, say CommonEvents, and then on my individual forms’ Load handlers assign the static method definition to the respective DataGridViews’ CellClick event
this.dgvParms.CellClick += CommonEvents.dgvEditOnCellClick;
Is this acceptable or good practice? Or is it preffered to keep event handler logic with each consuming form’s code? I could of course do something in between (but redundant) by defining local event handlers which then call the common method, such as
this.dgvParms.CellClick += (a, b) => CommonEvents.dgvEditOnCellClick(a, b);
This looks absolutely fine to me, although of course you will have to change you code to use the
senderargument to locate theDataGridViewthat raised the event:The general approach of changing or adding behaviour to a control by handling and reacting to its events is called an attached behaviour. It is most typically used in WPF, but there is nothing wrong with using it in WinForms too.